【问题标题】:How to create an instance of a subclass from the super class?如何从超类创建子类的实例?
【发布时间】:2019-06-28 23:17:48
【问题描述】:

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

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

【问题讨论】:

  • return new this;
  • @Keith 不起作用,它返回 this is not a constructor 错误
  • @InfiniteDev 是吗?为我工作……
  • Edge / Chrome / Firefox 中为我工作,您使用什么浏览器?不过,您看到的错误不是 Linting 错误吗?
  • 也可以在节点中使用,您使用的是什么版本的节点。?由于它基于 Chromes JS V8 引擎,因此在意料之中。

标签: javascript node.js ecmascript-6


【解决方案1】:

static method is called 及其 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方法中获取子类的一些静态属性
  • @AmarjitSingh 相同,只是this.staticProperty
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多