简体   繁体   English

如何将静态属性添加到ES6类

[英]How to add static attribute to ES6 class

We know very well that class of ES6 brought also : static , get as well as set features : 我们非常清楚ES6的class带来了: staticget以及set功能:

However , it seems that static keyword is reserved only for Methods : 但是,似乎static关键字仅保留给方法:

class Person {

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

How to be able to write static attribute within ES6 class to have something like the static attribute MIN . 如何能够在ES6类中编写static属性以获得类似静态属性MIN

We know that we can add the following instruction after class definition : 我们知道我们可以在类定义后添加以下指令:

Person.MIN=10; 

However , our scope is to find the way to write this instruction inside class block 但是,我们的范围是找到在类块中编写此指令的方法

You can use static getter: 你可以使用静态getter:

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

你需要一个方法来返回属性,否则它只能在类中访问,这会破坏你试图用静态做的事情。

You cannot reach your scope with ES6 unless static getter , however , you may can in ES7. 除非使用静态吸气器,否则无法通过ES6达到您的范围,但是,您可以在ES7中使用。

Anyway, Babel support now the wanted syntax (check http://babeljs.io/ ) : 无论如何, 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM