繁体   English   中英

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

[英]How to create an instance of a subclass from the super class?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM