如何从超类创建子类的实例? [英] How to create an instance of a subclass from the super class?

查看:252
本文介绍了如何从超类创建子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a class and its subclasses, where I am required to call a static method of the parent to return a child instance.

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

推荐答案

调用静态方法,其 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

这篇关于如何从超类创建子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆