如何从超类创建子类的实例?

时间:2018-06-21 09:09:40

标签: 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 extends Animal{
}

class Dog extends Animal{
}

const human = Human.findOne() //returns a Human instance
const day = Dog.findOne() //returns a Dog instance

1 个答案:

答案 0 :(得分:5)

值为this的{​​{3}}是类对象,即您调用它的子类的构造函数。因此,您可以使用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