如何在命名空间中创建私有变量?

Sta*_*eyI 10 javascript namespaces private-members

对于我的Web应用程序,我在JavaScript中创建一个名称空间,如下所示:

var com = {example: {}};
com.example.func1 = function(args) { ... }
com.example.func2 = function(args) { ... }
com.example.func3 = function(args) { ... }
Run Code Online (Sandbox Code Playgroud)

我也想创建"私有"(我知道这在JS中不存在)命名空间变量,但我不确定什么是最好的设计模式.

可不可能是:

com.example._var1 = null;
Run Code Online (Sandbox Code Playgroud)

或者设计模式是否是别的?

cdh*_*wie 8

闭包经常像这样用来模拟私有变量:

var com = {
    example: (function() {
        var that = {};

        // This variable will be captured in the closure and
        // inaccessible from outside, but will be accessible
        // from all closures defined in this one.
        var privateVar1;

        that.func1 = function(args) { ... };
        that.func2 = function(args) { ... } ;

        return that;
    })()
};
Run Code Online (Sandbox Code Playgroud)

  • 若要添加此答案:本文介绍了您应该考虑的模块模式的一些不同变体.http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth (2认同)

jir*_*ira 8

Douglas Crockford推广了所谓的模块模式,您可以使用"私有"变量创建对象:

myModule = function () {

        //"private" variable:
        var myPrivateVar = "I can be accessed only from within myModule."

        return  {
                myPublicProperty: "I'm accessible as myModule.myPublicProperty"
                }
        };

}(); // the parens here cause the anonymous function to execute and return
Run Code Online (Sandbox Code Playgroud)

但正如你所说Javascript并没有真正拥有私有变量,我认为这有点像一个破坏其他东西的淤泥.例如,尝试从该类继承.