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
Intervalia
source share