我有一个遵循JavaScript标准的ECMA6类,我想在其中创建一个静态变量。
为了实现这一点,我阅读了以下文档:
第一个链接演示如何在ECMA 6中的类中创建静态方法,而第二个链接演示如何使用prototype和函数来实现在ECMA6之前创建静态变量。
这些都不是我想要的。我在找这样的东西:
class AutoMobile {
constructor(name, license) {
//class variables (public)
this.name = name;
this.license = license;
}
//static variable declaration
static DEFAULT_CAR_NAME = "Bananas-Benz";
}但是,前面的示例无法工作,因为static关键字仅适用于方法。
如何使用JavaScript中的ECMA6在类中创建静态变量?
发布于 2016-05-27 09:51:14
您可以通过getter实现这一点:
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";
}
}并可通过以下方式访问:
const defaultCarName = AutoMobile.DEFAULT_CAR_NAME;类属性在ES2015中不受支持。
https://stackoverflow.com/questions/37480062
复制相似问题