samanime
samanime

Reputation: 26557

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.

Upvotes: 9

Views: 4548

Answers (2)

Intervalia
Intervalia

Reputation: 10945

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;
  }
}

Produces this error:

{
  "message": "Uncaught SyntaxError: Unexpected token =",
  "filename": "https://stacksnippets.net/js",
  "lineno": 19,
  "colno": 22
}

And this code:

class MyClass {
  dogs = (val) => {
   console.log('Bark, bark', val);
  }
}

produces this error:

{
  "message": "Uncaught SyntaxError: Unexpected token =",
  "filename": "https://stacksnippets.net/js",
  "lineno": 14,
  "colno": 12
}

This code:

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

Is just the ES5 version to this code:

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

This code:

class MyClass {}
MyClass.myProp = 1;

Is does attach myProp to the prototype of the class and is the equivalent of a static variable. But that value can be changed. So if you want a read only property then you need one of the above setters..

In this code:

class MyClass {
  static get myVal() {
    return 1;
  }
}
MyClass.yourVal = 33;

console.log(MyClass.myVal);
console.log(MyClass.yourVal);

We get the output of 1 and 33. Which is what was expected

Upvotes: 1

Bharat23
Bharat23

Reputation: 537

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.

Upvotes: 3

Related Questions