Member variables in ES6 classes

前端 未结 3 1270
日久生厌
日久生厌 2020-12-15 16:34

Is there any way to use the ECMAScript6 class notation to declare either a static class variable or a default value for an instance variable? Without clas

3条回答
  •  醉话见心
    2020-12-15 17:16

    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
    

提交回复
热议问题