相关疑难解决方法(0)

匿名类实例----这是个坏主意吗?

在ES6中我们可以做匿名类:

var entity = class {
}
Run Code Online (Sandbox Code Playgroud)

但我们也可以实例化它:

var entity = new class {
    constructor(name) { this.name = name; }
    getName() { return this.name; }
}('Foo');
console.log(entity.getName()); // Foo
Run Code Online (Sandbox Code Playgroud)

背后做了什么,它带来了什么好处以及它带来了什么警告?

javascript oop anonymous-function javascript-objects ecmascript-6

24
推荐指数
2
解决办法
1万
查看次数

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

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

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
Run Code Online (Sandbox Code Playgroud)

javascript node.js ecmascript-6

1
推荐指数
1
解决办法
205
查看次数