静态变量JavaScript ECMA6 [英] Static Variable JavaScript ECMA6
问题描述
为了达到这个目的,我阅读了以下文档:
第一个链接演示了如何创建ECMA 6中的类中的静态方法,而第二个链接演示了如何使用原型和函数来实现在ECMA6之前创建静态变量。
这不是我想要的。我正在寻找这样的东西:
class AutoMobile {
constructor(name,license){
//类变量(public)
this.name = name;
this.license =许可证;
}
//静态变量声明
static DEFAULT_CAR_NAME =Bananas-Benz;
}
然而,以前的例子不会工作,因为 static
关键字仅适用于方法。
如何使用ECMA6在JavaScript中创建一个静态变量?
你可以用getter来实现:
class AutoMobile {
构造函数(名称,许可证){
//类变量(public)
this.name = name;
this.license =许可证;
}
//静态变量声明
static get DEFAULT_CAR_NAME(){
returnBananas-Benz;
}
}
然后访问:
const defaultCarName = AutoMobile.DEFAULT_CAR_NAME;
ES2015不支持类属性。
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:
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 ?
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.
这篇关于静态变量JavaScript ECMA6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!