user318747
user318747

Reputation: 1428

Question about javascript namespaces

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 }
};

Upvotes: 2

Views: 573

Answers (1)

lambacck
lambacck

Reputation: 9926

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).

Upvotes: 11

Related Questions