I\'m trying to use a static variable in es6. I\'d like to declare a static variable count
in Animal
class and increase it. However, I couldn\'t declare
As mentioned in other answers, this.count
refers to instance property in constructor
. In order for static property to be initialized, Animal.count
should be set.
Class fields proposal provides syntactic sugar for Animal.count = 0
that is available with transpilers (Babel, etc):
class Animal {
static count = 0;
...
}
An alternative in ES6 is to use initial values, in this case Animal.count
initial value doesn't need to be set explicitly, e.g.:
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:
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
):
const animal = {
increaseCount() {
this.count += 1;
},
get count() {
return this._count || 0;
},
set count(v) {
this._count = v;
}
};