如何向ES6类添加静态属性

5
我们非常清楚ES6中的class引入了static、get和set功能。然而,似乎static关键字仅保留用于方法。
class Person {

    // static method --> No error
    static size(){
    }   
  // static attribute --> with Error
    static MIN=10;
}

如何在ES6类中编写具有像MIN静态属性的静态属性?
我们知道可以在类定义后添加以下指令:
Person.MIN=10; 

然而,我们的目标是找到一种方法,在类块内部编写此指令。

也许你应该查看一下 JS 规范,或许你能找到一种向 Crockford 提交功能请求的方法。 - Morteza Tourani
3个回答

10

您可以使用静态 getter:

class HasStaticValue {
  static get MIN() {
    return 10;
  }
}

console.log(HasStaticValue.MIN);


4

如果不使用静态getter,就无法用ES6访问作用域,但是在ES7中可能可以。

无论如何,Babel现在支持所需的语法(请查看http://babeljs.io/):

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'

2
你需要一个方法来返回属性,否则它仅在类内部可访问,这与你尝试使用静态的初衷背道而驰。

悲观主义者...我们需要一些乐观主义。 - Abdennour TOUMI

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接