Javascript ES6 shared class variable

主宰稳场 提交于 2020-04-07 03:48:06

问题


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.



来源:https://stackoverflow.com/questions/36922109/javascript-es6-shared-class-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!