11

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

var com = {example: {}};
com.example.func1 = function(args) { ... }
com.example.func2 = function(args) { ... }
com.example.func3 = function(args) { ... }

我还想创建“私有”(我知道这在 JS 中不存在)命名空间变量,但不确定使用的最佳设计模式是什么。

可不可能是:

com.example._var1 = null;

或者设计模式会是别的东西吗?

4

3 回答 3

9

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

但正如你所说,Javascript 并没有真正的私有变量,我认为这有点混乱,会破坏其他东西。例如,尝试从该类继承。

于 2010-11-10T20:36:25.353 回答
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;
    })()
};
于 2010-11-10T20:32:08.280 回答
0

7 年后这可能会来得很晚,但我认为这可能对其他有类似问题的程序员有用。

几天前,我想出了以下功能:

{
    let id    = 0;                          // declaring with let, so that id is not available from outside of this scope
    var getId = function () {               // declaring its accessor method as var so it is actually available from outside this scope
        id++;
        console.log('Returning ID: ', id);
        return id;
    }
}

这可能仅在您处于全局范围内并且想要声明一个无法从任何地方访问的变量时才有用,除非您的函数将 id 的值设置为一个并返回其值。

于 2018-08-31T13:27:06.943 回答