Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何向ES6类添加静态属性_Javascript_Oop_Static_Attributes_Ecmascript 6 - Fatal编程技术网

Javascript 如何向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的特性 我们知道我们可以在类定义之后添

我们非常清楚,ES6的
也带来了:
静态
获取
以及
设置
功能:

但是,似乎
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'