Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter with arrow function syntax

Is there a JavaScript syntax that lets me do the following more succinctly?

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

It is 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.

like image 373
samanime Avatar asked May 15 '17 15:05

samanime


Video Answer


1 Answers

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.

like image 83
Bharat23 Avatar answered Oct 20 '22 02:10

Bharat23