Javascript ES6共享类变量 [英] Javascript ES6 shared class variable
本文介绍了Javascript ES6共享类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的课:
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;
现在我想做同样的事情,但是在类的所有实例之间共享_some_obj
.
Now I want to do the same thing but with _some_obj
shared between all instances of the class.
经过搜索后,我不清楚在ES6中执行此操作的正确方法.
After searching around I'm unclear as to the correct way to do this in ES6.
推荐答案
从ES5开始,您可以将其放在类的原型对象上:
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
});
或直接在Foo
上(如果您不需要作为实例的属性来访问它).
Or directly on Foo
, if you don't need to access it as a property on instances.
这篇关于Javascript ES6共享类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文