是否有正确的方法来创建无论您创建多少次都不会更改的私有new Obj
静态 javascript 变量(和函数) ?
这是我尝试过的,它似乎有效:
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`
还是有其他 更好的方法?