Member variables in ES6 classes

巧了我就是萌 提交于 2019-11-29 01:02:47

ES6 will almost certainly not cover syntax for defining class variables. Only methods and getters/setters can be defined using the class syntax. This means you'll still have to go the MyClass.classVariable = 42; route for class variables.

If you just want to initialize a class with some defaults, there is a rich new syntax set for function argument and destructuring defaults you can use. To give a simple example:

class Foo {
    constructor(foo = 123) {
        this.foo = foo;
    }
}

new Foo().foo == 123
new Foo(42).foo == 42

I haven't used Google Closure Compiler, but with Babel you can declare static (scoped to a class) variables as described here. The article is focused on React because of the utility of static members for React, but is applicable to ES6 classes in general.

Syntax is close to your proposed syntax:

class MyClass {
    constructor(arg) { if(arg) this.arg = arg; }
    static defaultArg = 42;
    let arg = MyClass.defaultArg;
}

Note that you'll have to add 'es7.classProperties' to your .babelrc for this to compile. See the Babel 5.0.0 release notes for more info.

I don't know if there's a way to declare a static as a const.

While it's not part of the ES6 spec, this looks like it's coming soon and is already supported by Babel and some others.

Here's the spec: https://github.com/jeffmo/es-class-fields-and-static-properties

And a full list of all the proposals and their status: https://github.com/tc39/ecma262

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!