2

What is the point of returning methods in the following example when you can accomplish the same thing by just declaring the NS straightforward in the second code snippet?

1:

var NS = function() {
    return {
        method_1 : function() {
            // do stuff here
        },
        method_2 : function() {
            // do stuff here
        }
    };
}();

2:

var NS = {
    method_1 : function() { do stuff },
    method_2 : function() { do stuff }
};

1 Answer 1

11

In your particular example there is no advantage. But you can use the first version to hide some variables:

var NS = function() {
    var private = 0;
    return {
        method_1 : function() {
            // do stuff here
            private += 1;
        },
        method_2 : function() {
            // do stuff here
            return private;
        }
    };
}();

This is referred to as a Module in Douglas Crockford's "JavaScript: The Good Parts". If you search the web you should be able to find full explanations.

Basically the only thing that creates a new variable scope in Javascript is a function, so most global abatement revolves around either using properties of an object (NS in this case) or using a function to create a variable scope (the private var in this example).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.