Javascript 如何从超类创建子类的实例?
我正在创建一个类及其子类,需要调用父类的静态方法来返回子实例Javascript 如何从超类创建子类的实例?,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,我正在创建一个类及其子类,需要调用父类的静态方法来返回子实例 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 ex
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
它的this
值是类对象,是调用它的子类的构造函数。因此,您可以使用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
返回新的
@Keith不起作用,它返回这不是构造函数
error@InfiniteDev是吗?适用于我…适用于我在Edge
/Chrome
/Firefox
,你使用什么浏览器?不过,您看到的错误不是一个Linting错误,是吗?也适用于node,您使用的node版本是什么。?它基于Chromes JS V8引擎,所以有点像预期的那样。如何在findOne中获得子类的一些静态属性method@AmarjitSingh相同,只是this.staticProperty