Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
};
like image 726
user318747 Avatar asked Apr 10 '26 20:04

user318747


1 Answers

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

like image 71
lambacck Avatar answered Apr 13 '26 11:04

lambacck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!