如何在命名空间中创建私有变量? [英] How to create private variables within a namespace?
问题描述
对于我的Web应用程序,我在JavaScript中创建一个命名空间,如下所示:
For my web application, I am creating a namespace in JavaScript like so:
var com = {example: {}};
com.example.func1 = function(args) { ... }
com.example.func2 = function(args) { ... }
com.example.func3 = function(args) { ... }
我也想创建私人(我知道这不是'存在于JS)命名空间变量中,但不确定使用的最佳设计模式是什么。
I also want to create "private" (I know this doesn't exist in JS) namespace variables but am not sure what's the best design pattern to use.
是否:
com.example._var1 = null;
或者设计模式是别的吗?
Or would the design pattern be something else?
推荐答案
Douglas Crockford推广所谓的模块模式您可以使用私有变量创建对象:
Douglas Crockford popularized so called Module Pattern where you can create objects with "private" variables:
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没有真的有私人变量,我认为这有点像一个破坏其他东西的淤泥。例如,尝试从该类继承。
But as you said Javascript doesn't truly have private variables and I think this is somewhat of a cludge, which break other things. Just try to inherit from that class, for example.
这篇关于如何在命名空间中创建私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!