There is an ECMAScript Stage 3 proposal called Class Fields by Daniel Ehrenberg and Jeff Morrison, whose goal is to solve this problem.
class MyClass { static myStaticProp = 42; myProp = 42; myProp2 = this.myProp; myBoundFunc = () => { console.log(this.myProp); }; constructor() { console.log(MyClass.myStaticProp);
The above is equivalent to:
class MyClass { constructor() { this.myProp = 42; this.myProp2 = this.myProp; this.myBoundFunc = () => { console.log(this.myProp); }; console.log(MyClass.myStaticProp);
Babel supports passing class fields via @ babel / plugin-proposal-class-properties (included in pre-launch-3 ) so you can use this function even if your JavaScript runtime does not support it.
Compared to the @kangax getter declaration solution, this solution can also be more efficient, since here the resource is accessed directly, and not through a function call.
If this proposal is accepted, then it will be possible to write JavaScript code in a way that is more like traditional object-oriented languages such as Java and C♯.
Edit: the class offer of unified classes is now at stage 3; upgrade your Babel v7.x packages.
Timothy Gu Aug 02 '16 at 18:18 2016-08-02 18:18
source share