Getter with arrow function syntax

Is there any JavaScript syntax that lets me do the following more succinctly:

class MyClass {
    static get myProp() {
        return 1;
    }
}

Not a huge deal, but I'd like to know if there was something that was like an arrow function that lets me make it just a little more streamlined, something like:

class MyClass {
    static get myProp = () => 1;
}

I know I could write it like this (though not a safe equivalent):

class MyClass {}
MyClass.myProp = 1;

Or this more difficult to read and longer alternative:

class MyClass {}
Object.define(MyClass, 'myProp', { get: () => 1; });

but that feels like an abuse of the class syntax


There is a better way to do it. It can be done using Babel Preset for class-transform. The preset to get this particular feature is 'preset-stage-2'.

The documentation page of babel for preset-stage-2: https://babeljs.io/docs/plugins/preset-stage-2/

Use Case: In your .bablerc file ad the present.

{
  "presets": ["stage-2"]
}

Note : it is a separate npm module so install it beforehand.


You can't use arrow functions to define class functions within a class declaration. Attempting to do so generates a syntax error.

The following code:

class MyClass {
  static get myVal() {
    console.log(this);
    return 1;
  }

  static get yourVal = () => {
    console.log(this);
    return 2;
  }
}
链接地址: http://www.djcxy.com/p/39380.html

上一篇: 在Angular 4中的组件上应用属性指令

下一篇: 带箭头函数语法的Getter