Javascript 如何向ES6类添加静态属性
我们非常清楚,ES6的Javascript 如何向ES6类添加静态属性,javascript,oop,static,attributes,ecmascript-6,Javascript,Oop,Static,Attributes,Ecmascript 6,我们非常清楚,ES6的类也带来了:静态,获取以及设置功能: 但是,似乎static关键字仅保留给方法: class Person { // static method --> No error static size(){ } // static attribute --> with Error static MIN=10; } 如何在ES6类中编写static属性,使其具有类似static属性MIN的特性 我们知道我们可以在类定义之后添
类
也带来了:静态
,获取
以及设置
功能:
但是,似乎static
关键字仅保留给方法:
class Person {
// static method --> No error
static size(){
}
// static attribute --> with Error
static MIN=10;
}
如何在ES6类中编写static
属性,使其具有类似static属性MIN
的特性
我们知道我们可以在类定义之后添加以下指令:
Person.MIN=10;
但是,我们的工作范围是找到在类块中编写此指令的方法。您需要一个方法来返回属性,否则它只能在类中访问,这就破坏了您尝试使用静态方法的目的 您可以使用静态getter:
类HasStaticValue{
静态get MIN(){
返回10;
}
}
console.log(HasStaticValue.MIN)代码>除非使用静态getter,否则ES6无法达到您的范围,但是,您可以使用ES7
无论如何,现在支持所需的语法(检查):
悲观主义者。。我们需要一些乐观主义者。也许你应该检查一下JS
spec,也许你能找到一种方法向crockford发送功能请求。
class Foo {
bar = 2
static iha = 'string'
}
const foo = new Foo();
console.log(foo.bar, foo.iha, Foo.bar, Foo.iha);
// 2, undefined, undefined, 'string'