【问题标题】:How to create private variables within a namespace?如何在命名空间中创建私有变量?
【发布时间】:2011-05-08 02:46:13
【问题描述】:

对于我的 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;

或者设计模式会是别的什么?

【问题讨论】:

  • “伟大”是指“创造”吗?
  • @casablanca,不-我的问题也与您链接的内容不重复。
  • @Staceyl:我链接到的问题有一个如何在命名空间中创建私有变量的示例。
  • @Staceyl:第一次上谷歌,搜索“javascript private member”:crockford.com/javascript/private.html

标签: javascript namespaces private-members


【解决方案1】:

Douglas Crockford 推广了所谓的 Module Pattern,您可以在其中使用“私有”变量创建对象:

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 并没有真正的私有变量,我认为这有点混乱,会破坏其他东西。例如,尝试从该类继承。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    【解决方案3】:

    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 的值设置为一个并返回其值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-26
      • 2017-12-30
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2020-03-02
      相关资源
      最近更新 更多