Getter with arrow function syntax

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

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

It doesn’t matter, but I would like to know if there was something like an arrow function that allows me to make it a little more streamlined, something like:

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

I know that I can write it like this (although not a safe equivalent):

 class MyClass {} MyClass.myProp = 1; 

Or is it harder to read a longer alternative:

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

but it looks like class syntax abuse

+7
javascript ecmascript-6
source share
2 answers

There is a better way to do this. This can be done using Babel Preset to convert the class. The preset for getting this function is "preset-stage-2".

Babel documentation page for predefined scene-2: https://babeljs.io/docs/plugins/preset-stage-2/

Use Case: In your .bablerc ad.

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

Note : this is a separate npm module, so install it in advance.

+2
source share

You cannot use arrow functions to define class functions in a class declaration. Trying to do this creates 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); } } 

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

This is only the ES5 version for this code:

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

This code:

 class MyClass {} MyClass.myProp = 1; 

Is attaches myProp to the prototype of the class and is the equivalent of a static variable. But this value can be changed. Therefore, if you want a read-only property, you will need one of the above devices.

In this code:

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

Get the output 1 and 33 . As expected

0
source share

All Articles