javascript,polymorphic new Myclass()?

时间:2016-10-27 03:14:58

标签: javascript class ecmascript-6

我有很多具有以下形式的课程。

static defaultInstance() {

 if (!defaultInstance) {
   defaultInstance = new Child1()
 }
 return defaultInstance
}

由于它们有一个共同的基类,我想将基本功能添加到基类,但不知道如何。
(遇到新Child1()的问题)

1 个答案:

答案 0 :(得分:1)

如果Child1应该引用“当前”类,即调用defaultInstance的类,那么你可以这样做

defaultInstance = new this();

这符合正常的JavaScript规则:如果您使用Child1.defaultInstance()调用该函数,则this会引用Child1

然而,这可能不会做你想要的。如果在基类上定义defaultInstance,则所有子类共享相同的 defaultInstance变量。

如果你想要一个实例 per 类,那么每个类都需要自己的defaultInstance方法,或者你需要使用一个属性,例如。

if (!this.__defaultInstance) {
  this.__defaultInstance = new this();
}