Javascript ES6 shared class variable

2020-04-07 19:01发布

问题:

I have a class that looks like this:

class Foo {
    constructor(arg1, arg2) {
        // ...

        this._some_obj = new SomeObj({
            param1: arg1,
            param2: arg2
        });
    }

    // ...
}

module.exports = Foo;

Now I want to do the same thing but with _some_obj shared between all instances of the class.

After searching around I'm unclear as to the correct way to do this in ES6.

回答1:

As known from ES5, you can just put it on the class's prototype object:

export class Foo {
    constructor(arg1, arg2) {
        …
    }
    …
}
Foo.prototype._some_obj = new SomeObj({
    param1: val1,
    param2: val2
});

Or directly on Foo, if you don't need to access it as a property on instances.



回答2:

Use static to have class properties.

class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // Prints '42'
  }
}

N.B: this is a feature already implemented in Babel, but is still experimental as only at the 1st proposal stage.