如何在Javascript中创建静态变量?
当前回答
还有其他类似的答案,但没有一个对我很有吸引力
var nextCounter = (function () {
var counter = 0;
return function() {
var temp = counter;
counter += 1;
return temp;
};
})();
其他回答
我使用了原型,并以这种方式工作:
class Cat {
constructor() {
console.log(Cat.COLLECTION_NAME);
}
}
Cat.COLLECTION_NAME = "cats";
或使用静态吸气剂:
class Cat {
constructor() {
console.log(Cat.COLLECTION_NAME);
}
static get COLLECTION_NAME() {
return "cats"
}
}
JavaScript中最接近静态变量的是一个全局变量——这只是一个在函数或对象文本范围之外声明的变量:
var thisIsGlobal = 1;
function foo() {
var thisIsNot = 2;
}
您可以做的另一件事是将全局变量存储在对象文本中,如下所示:
var foo = { bar : 1 }
然后像这样访问变量:foo.bar。
{
var statvar = 0;
function f_counter()
{
var nonstatvar = 0;
nonstatvar ++;
statvar ++;
return statvar + " , " + nonstatvar;
}
}
alert(f_counter());
alert(f_counter());
alert(f_counter());
alert(f_counter());
这只是我在某处学到的另一种静态变量的方法。
试试这个:
如果我们定义一个属性并重写其getter和setter以使用Function Object属性,那么理论上可以在javascript中使用一个静态变量
例如:
函数Animal(){if(isNaN(this.totalAnimalCount)){this.totalAnimalCount=0;}this.totalAnimationCount++;};Object.defineProperty(动画原型,“totalAnimalCount”{获取:函数(){return Animal['totalAnimalCount'];},集合:函数(val){动物['totalAnimalCount']=val;}});var cat=新动画();console.log(cat.totalAnimationCount)//将产生1var dog=新动画();console.log(cat.totalAnimationCount)//将产生2等。
ES6类支持静态函数,其行为与其他面向对象语言中的静态函数非常相似:
class MyClass {
static myFunction() {
return 42;
}
}
typeof MyClass.myFunction; // 'function'
MyClass.myFunction(); // 42
通用静态财产仍然是第三阶段的建议,这意味着您需要巴贝尔的第三阶段预设才能使用它们。但有了Babel,你可以做到这一点:
class MyClass {
static answer = 42;
}
MyClass.answer; // 42