对于我的 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;
或者设计模式会是别的什么吗?
道格拉斯·克罗克福德 (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 并没有真正的私有变量,我认为这有点麻烦,它破坏了其他东西。例如,尝试从该类继承。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)