Javascript 如何在 ES6 类中使用静态变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51381966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a static variable in ES6 class?
提问by Caesium133
I'm trying to use a static variable in es6. I'd like to declare a static variable countin Animalclass and increase it. However, I couldn't declare a static variable through static count = 0;, so I tried another way like this:
我正在尝试在 es6 中使用静态变量。我想count在Animal类中声明一个静态变量并增加它。但是,我无法通过 声明静态变量static count = 0;,所以我尝试了另一种方法:
class Animal {
constructor() {
this.count = 0;
}
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
console.log(Animal.increaseCount()); // undefined
console.log(Animal.getCount()); // NaN
I expected console.log(Animal.getCount());to be 1, but it doesn't work.
How do I declare a static variable and modify it by calling a method?
我希望console.log(Animal.getCount());是1,但它不起作用。如何声明静态变量并通过调用方法对其进行修改?
回答by T.J. Crowder
Your class has no static variables (if by static variable you mean static property). getCountreturns NaN(after you call increaseCount) because Animalhas no countproperty initially. Then increaseCountdoes undefined + 1which is NaN. Instancescreated by new Animalhave a countproperty initially, but Animalitself does not until you call increaseCount. thiswithin a staticmethod refers to the Animalclass (constructor function) itself (if you call it via Animal.methodName(...)).
您的类没有静态变量(如果静态变量是指静态属性)。getCount返回NaN(在您调用之后increaseCount),因为最初Animal没有count属性。然后increaseCount呢undefined + 1这是NaN。创建的实例最初new Animal有一个count属性,但Animal直到您调用increaseCount. 方法this内是static指Animal类(构造函数)本身(如果您通过 调用它Animal.methodName(...))。
You could give Animala countproperty:
你可以给Animal一个count属性:
Animal.count = 0;
Live Example:
现场示例:
class Animal {
constructor() {
}
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
Animal.count = 0;
Animal.increaseCount();
console.log(Animal.getCount());
Animal.increaseCount();
console.log(Animal.getCount());
With the static class fields proposal(currently at Stage 3), you could do that declaratively with static count = 0;in Animal. Live Example (Stack Snippets' Babel configuration seems to support it):
使用静态类字段提案(目前处于第 3 阶段),您可以使用static count = 0;in声明性地做到这一点Animal。实时示例(Stack Snippets 的 Babel 配置似乎支持它):
class Animal {
constructor() {
}
static count = 0;
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
Animal.increaseCount();
console.log(Animal.getCount());
Animal.increaseCount();
console.log(Animal.getCount());
With the private staticproposal (at Stage 3 and actively being implemented), you could even make countprivate:
使用私有静态提案(在第 3 阶段并正在积极实施),您甚至可以将其count设为私有:
class Animal {
constructor() {
}
static #count = 0;
static increaseCount() {
this.#count += 1;
}
static getCount() {
return this.#count;
}
}
Animal.increaseCount();
console.log(Animal.getCount());
Animal.increaseCount();
console.log(Animal.getCount());
Stack Snippets' Babel config doesn't support that, but you can run it live in their REPL.
Stack Snippets 的 Babel 配置不支持这一点,但您可以在他们的 REPL 中实时运行它。
Side note: Using thiswithin a static method to refer to the class (constructor function) is a bit tricky if there are subclasses, because for instance, if you had:
旁注:this如果有子类,在静态方法中使用来引用类(构造函数)有点棘手,因为例如,如果你有:
class Mammal extends Animal {}
and then
进而
Mammal.increaseCount();
thiswithin increaseCount(which it inherits from Animal) refers to Mammal, not Animal.
this内increaseCount(它继承自Animal)指的是Mammal,而不是Animal。
If you wantthat behavior, use this. If you don't, use Animalin those staticmethods.
如果您想要这种行为,请使用this. 如果不这样做,请Animal在这些static方法中使用。
回答by Estus Flask
As mentioned in other answers, this.countrefers to instanceproperty in constructor. In order for staticproperty to be initialized, Animal.countshould be set.
正如在其他的答案中提到,this.count是指例如在财产constructor。为了初始化静态属性,Animal.count应该设置。
Class fields proposalprovides syntactic sugar for Animal.count = 0that is available with transpilers (Babel, etc):
类字段提案为Animal.count = 0转译器(Babel 等)提供了语法糖:
class Animal {
static count = 0;
...
}
An alternative in ES6 is to use initial values, in this case Animal.countinitial value doesn't need to be set explicitly, e.g.:
ES6 中的另一种方法是使用初始值,在这种情况下,Animal.count不需要显式设置初始值,例如:
class Animal {
static increaseCount() {
this.count = this.getCount() + 1;
}
static getCount() {
return this.count || 0;
}
}
Accessor methods aren't welcome in JavaScript classes - this is what getter/setter descriptors are for:
JavaScript 类中不欢迎访问器方法 - 这就是 getter/setter 描述符的用途:
class Animal {
static increaseCount() {
this.count += 1;
}
static get count() {
return this._count || 0;
}
static set count(v) {
this._count = v;
}
}
Static-only class is considered antipattern in JavaScript because a state or other traits that are specific to classes aren't used. In case there should be only one instance, plain object should be used (unless there are other concerns that could benefit from class):
仅静态类在 JavaScript 中被视为反模式,因为不使用特定于类的状态或其他特征。如果应该只有一个实例,则应该使用普通对象(除非有其他可以从 中受益的问题class):
const animal = {
increaseCount() {
this.count += 1;
},
get count() {
return this._count || 0;
},
set count(v) {
this._count = v;
}
};
回答by mpm
To set a static variable, set it on the object Animal itself. As of now in Javascript you cannot directly declare static properties inside classes like you can declare static methods.
要设置静态变量,请将其设置在对象 Animal 本身上。截至目前,在 Javascript 中,您不能像声明静态方法那样直接在类中声明静态属性。
class Animal {
constructor() {
}
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
Animal.count = 0;
console.log(Animal.increaseCount());
console.log(Animal.getCount());
回答by Farooq Hanif
Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration.
静态类端属性和原型数据属性必须在 ClassBody 声明之外定义。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
class Animal {
static increaseCount() {
Animal.count += 1;
}
static getCount() {
return Animal.count;
}
}
Animal.count = 0;
Animal.increaseCount();
console.log(Animal.getCount()); // undefined

