我有许多具有以下形式的类。
static defaultInstance() {
if (!defaultInstance) {
defaultInstance = new Child1()
}
return defaultInstance
}
由于它们有一个共同的基类,我想将共同的功能添加到基类中,但不知道如何。
(使用 new Child1() 时遇到问题)
最佳答案
如果 Child1
应该引用“当前”类,即调用 defaultInstance
的类,那么您可以这样做
defaultInstance = new this();
这遵循正常的 JavaScript 规则:如果您使用 Child1.defaultInstance()
调用该函数,则 this
引用 Child1
。
但是,这可能不会达到您想要的效果。如果您在基类上定义 defaultInstance
,则所有子类共享相同 defaultInstance
变量。
如果您希望每个类都有一个实例,那么每个类都需要有自己的 defaultInstance
方法,或者您需要使用属性,例如
if (!this.__defaultInstance) {
this.__defaultInstance = new this();
}
关于javascript,多态 new Myclass()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275519/