如何在Javascript中创建静态变量?
当前回答
ES6类支持静态函数,其行为与其他面向对象语言中的静态函数非常相似:
class MyClass {
static myFunction() {
return 42;
}
}
typeof MyClass.myFunction; // 'function'
MyClass.myFunction(); // 42
通用静态财产仍然是第三阶段的建议,这意味着您需要巴贝尔的第三阶段预设才能使用它们。但有了Babel,你可以做到这一点:
class MyClass {
static answer = 42;
}
MyClass.answer; // 42
其他回答
Javascript中没有静态变量。这种语言是基于原型的面向对象的,因此没有类,而是对象“复制”自己的原型。
您可以使用全局变量或原型(向原型添加属性)来模拟它们:
function circle(){
}
circle.prototype.pi=3.14159
我通常使用这种方法有两个主要原因:
如果我想存储函数的本地值,我会使用“local.x”、“local.y”、“local.TempData”等。。。!
如果我想存储函数的静态值,我会使用“static.o”、“static.Info”、“static.count”等。。。!
[Update2]:方法相同,但使用IIFE方法!
[Update1]:通过预编辑脚本自动创建函数的“静态”和“本地”对象!
JavaScript中最接近静态变量的是一个全局变量——这只是一个在函数或对象文本范围之外声明的变量:
var thisIsGlobal = 1;
function foo() {
var thisIsNot = 2;
}
您可以做的另一件事是将全局变量存储在对象文本中,如下所示:
var foo = { bar : 1 }
然后像这样访问变量:foo.bar。
您可以在JavaScript中创建一个静态变量,如下所示。这里count是静态变量。
var Person = function(name) {
this.name = name;
// first time Person.count is undefined, so it is initialized with 1
// next time the function is called, the value of count is incremented by 1
Person.count = Person.count ? Person.count + 1 : 1;
}
var p1 = new Person('User p1');
console.log(p1.constructor.count); // prints 1
var p2 = new Person('User p2');
console.log(p2.constructor.count); // prints 2
您可以使用Person函数或任何实例为静态变量赋值:
// set static variable using instance of Person
p1.constructor.count = 10; // this change is seen in all the instances of Person
console.log(p2.constructor.count); // prints 10
// set static variable using Person
Person.count = 20;
console.log(p1.constructor.count); // prints 20
关于ECMAScript 2015引入的类。其他答案并不完全清楚。
下面是一个示例,演示如何使用ClassName.var synthax创建静态var-staticVar:
class MyClass {
constructor(val) {
this.instanceVar = val;
MyClass.staticVar = 10;
}
}
var class1 = new MyClass(1);
console.log(class1.instanceVar); // 1
console.log(class1.constructor.staticVar); // 10
// New instance of MyClass with another value
var class2 = new MyClass(3);
console.log(class1.instanceVar); // 1
console.log(class2.instanceVar); // 3
为了访问静态变量,我们使用.constructor属性,该属性返回对创建类的对象构造函数的引用。我们可以在两个创建的实例上调用它:
MyClass.staticVar = 11;
console.log(class1.constructor.staticVar); // 11
console.log(class2.constructor.staticVar); // 11 <-- yes it's static! :)
MyClass.staticVar = 12;
console.log(class1.constructor.staticVar); // 12
console.log(class2.constructor.staticVar); // 12