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

IT技术 javascript node.js ecmascript-6
2021-02-06 03:58:04

我正在创建一个类及其子类,我需要在其中调用父类的静态方法以返回子实例。

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个回答

静态方法被调用,其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
findOne方法中如何获取子类的一些静态属性
2021-04-08 03:58:04
@AmarjitSingh 同样,只是 this.staticProperty
2021-04-08 03:58:04