在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
我正在创建一个类及其子类,需要在其中调用父级的静态方法以返回子级实例。
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)