Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从超类创建子类的实例?_Javascript_Node.js_Ecmascript 6 - Fatal编程技术网

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

Javascript 如何从超类创建子类的实例?,javascript,node.js,ecmascript-6,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 ex

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

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

返回新的
@Keith不起作用,它返回
这不是构造函数
error@InfiniteDev是吗?适用于我…适用于我在
Edge
/
Chrome
/
Firefox
,你使用什么浏览器?不过,您看到的错误不是一个Linting错误,是吗?也适用于node,您使用的node版本是什么。?它基于Chromes JS V8引擎,所以有点像预期的那样。如何在findOne中获得子类的一些静态属性method@AmarjitSingh相同,只是
this.staticProperty