简体   繁体   English

类静态属性

[英]Class static properties

In the new ES6 Class syntax it is not possible to do 在新的ES6 Class语法中,不可能这样做

class Person {
    this.type = 'person';

But if I define the property inside the contructor it works : 但是如果我在构造函数中定义属性它可以工作

class Person {
    constructor(name) { //class constructor
        this.name = name;
        this.type = 'person';
    }

I know the possibility to have properties outside methods is being discussed but as of today and what relates to the ES6 specs it is not possible. 我知道有属性之外的方法的可能性正在讨论中 ,但今天和什么涉及到ES6规格是不可能的。

Is my solution a correct way to define static properties for the Class (for semantic reasons I defined those properties inside the constructor but it seems to work inside other methods)? 我的解决方案是为类定义静态属性的正确方法(出于语义原因,我在构造函数中定义了这些属性,但它似乎在其他方法中工作)? Is there a better way? 有没有更好的办法?

I was looking at the spec in Method Defenition and found no information about this. 我正在查看Method Defenition中的规范, 没有找到关于此的信息。

You can create static getter: 您可以创建静态getter:

 "use strict"; class Person { static get type() { return 'person' } } console.log(Person.type) // 'person' 

As already said, what you are doing is creating an instance property. 如前所述,您正在做的是创建实例属性。 Adding such properties in the constructor is what the constructor is there for. 在构造函数中添加这些属性是构造函数的用途。 This hasn't changed with ES6. 这与ES6没有改变。

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

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