javascript – 如何在命名空间中创建私有变量?
作者:互联网
对于我的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;
或者设计模式是否是别的?
解决方法:
闭包经常像这样用来模拟私有变量:
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;
})()
};
标签:javascript,namespaces,private-members 来源: https://codeday.me/bug/20191006/1861595.html