是否有正确的方法来创建私有静态javascript变量(和函数),无论您创建new Obj
多少次都不会更改?< / p>
这是我尝试的,似乎工作:
var ObjClass = (function(){
var static_var = 0; //private static variable
var static_fn = function(){ return static_var; }; //private static function
return function(){
++static_var;
var thisNumber = static_var;
this.getThisNumber = function(){
return thisNumber;
}
this.getStaticNumber = static_fn; //making static fn public
}
})();
var obj1 = new ObjClass;
var obj2 = new ObjClass;
var obj3 = new ObjClass;
console.log(obj1.getThisNumber()); //output `1`
console.log(obj1.getStaticNumber()); //output `3`
console.log(obj2.getThisNumber()); //output `2`
console.log(obj2.getStaticNumber()); //output `3`
console.log(obj3.getThisNumber()); //output `3`
console.log(obj3.getStaticNumber()); //output `3`
还是有一些其他 更好 的方式?
答案 0 :(得分:5)
是的,这是创建私有静态变量的正确方法。
但是,我会认为static_fn
不同。看来你希望它是公开的。
Function
对象,因此可以使用任何其他js对象扩展属性。var ObjClass = (function closure(){
var static_var = 0; //static private (scoped) variable
function static_fn(){ return static_var; }; //static private (scoped) function
function ObjClass() {
var thisNumber = ++static_var; // private instance variable
this.getThisNumber = function() { // public instance method
return thisNumber; // "privileged" to access scoped instance variables
};
}
ObjClass.getStaticNumber = static_fn; // make the static_fn public
return ObjClass;
})();
var obj1 = new ObjClass;
var obj2 = new ObjClass;
console.log(ObjClass.getStaticNumber()); //output `2`
var obj3 = new ObjClass;
console.log(ObjClass.getStaticNumber()); //output `3`
console.log(obj1.getThisNumber()); //output `1`
console.log(obj2.getThisNumber()); //output `2`
console.log(obj3.getThisNumber()); //output `3`
答案 1 :(得分:1)
我以前使用这种简单的方法来创建静态变量,除了它们是私有的。
function MyClass() {
var static = this.constructor.static = this.constructor.static || {
var1: defValue,
...
}
static.var1 = ... ;
}
即。只需将静态变量存储为类的主构造函数的属性。