我正在创建一个类及其子类,其中需要调用父类的静态方法以返回子实例。
class Animal{
static findOne(){
// this has to return either an instance of Human
// or an instance of Dog according to what calls it
// How can I call new Human() or new Dog() here?
}
}
class Human extends Animal{
}
class Dog extends Animal{
}
const human = Human.findOne() //returns a Human instance
const day = Dog.findOne() //returns a Dog instance
The 静态方法被调用以其this
value 是类对象,您调用它的子类的构造函数。所以你可以实例化它new
:
class Animal {
static findOne() {
return new this;
}
}
class Human extends Animal{
}
class Dog extends Animal{
}
const human = Human.findOne() // returns a Human instance
const dog = Dog.findOne() // returns a Dog instance
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)