问题
I have a JavaScript class following the ECMA6 standard, and I would like to create a static variable in it.
To achieve this I read the following documentation:
- JavaScript Static keyword MDN
- Static variables in JavaScript
The first link demonstrates how one can create static methods inside a class in ECMA 6, while the second link demonstrates how you can use prototype and functions to achieve the creation of static variables prior to ECMA6.
None of this is what I want. I am looking for something like this:
class AutoMobile {
constructor(name, license) {
//class variables (public)
this.name = name;
this.license = license;
}
//static variable declaration
static DEFAULT_CAR_NAME = "Bananas-Benz";
}
However, the previous example wont work because the static
keyword is for methods only.
How can I create a static variable inside a class in JavaScript using ECMA6 ?
回答1:
You can achieve this with getters:
class AutoMobile {
constructor(name, license) {
//class variables (public)
this.name = name;
this.license = license;
}
//static variable declaration
static get DEFAULT_CAR_NAME() {
return "Bananas-Benz";
}
}
And access it with:
const defaultCarName = AutoMobile.DEFAULT_CAR_NAME;
Class properties are not supported in ES2015.
来源:https://stackoverflow.com/questions/37480062/static-variable-javascript-ecma6