关于javascript命名空间的问题

use*_*747 2 javascript namespaces

通过在第二个代码片段中直接声明NS,可以完成同样的事情,以下示例中返回方法的重点是什么?

1:

var NS = function() {
    return {
        method_1 : function() {
            // do stuff here
        },
        method_2 : function() {
            // do stuff here
        }
    };
}();
Run Code Online (Sandbox Code Playgroud)

2:

var NS = {
    method_1 : function() { do stuff },
    method_2 : function() { do stuff }
};
Run Code Online (Sandbox Code Playgroud)

lam*_*cck 11

在您的特定示例中,没有任何优势.但您可以使用第一个版本来隐藏一些变量:

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

这在Douglas Crockford的"JavaScript:The Good Parts"中被称为模块.如果您在网上搜索,您应该能够找到完整的解释.

基本上,在Javascript中创建新变量范围的唯一事情是函数,因此大多数全局减少围绕使用对象的属性(在本例中为NS)或使用函数创建变量范围(本示例中的私有变量) ).