我有很多具有以下形式的课程。
static defaultInstance() {
if (!defaultInstance) {
defaultInstance = new Child1()
}
return defaultInstance
}
由于它们有一个共同的基类,我想将基本功能添加到基类,但不知道如何。
(遇到新Child1()的问题)
答案 0 :(得分:1)
如果Child1
应该引用“当前”类,即调用defaultInstance
的类,那么你可以这样做
defaultInstance = new this();
这符合正常的JavaScript规则:如果您使用Child1.defaultInstance()
调用该函数,则this
会引用Child1
。
然而,这可能不会做你想要的。如果在基类上定义defaultInstance
,则所有子类共享相同的 defaultInstance
变量。
如果你想要一个实例 per 类,那么每个类都需要自己的defaultInstance
方法,或者你需要使用一个属性,例如。
if (!this.__defaultInstance) {
this.__defaultInstance = new this();
}