我正在尝试创建一个生成新实例的静态函数。该实例属于静态函数所属的类。
这是一个例子
class A {
static getInstance() {
return new A();
}
}
到目前为止一切顺利
let a = A.getInstance();
会正常工作。我想在子类中继承这个功能。
class B extends A {}
let b = B.getInstance(); // This will return an instance of A.
我要
B.getInstance()
返回 B 的一个实例。
最佳答案
这似乎可行。我假设您想要这个,因为您想将一个类作为某种构造函数/生成器传递。就像做 new A()
显然要简单一些。
class A {
sayIt() { console.log('I am A'); }
static getInstance() {
return new this;
}
}
class B extends A { sayIt() { console.log('I am B') } }
var k = A.getInstance();
k.sayIt();
let b = B.getInstance();
b.sayIt();
let k2 = new A();
k2.sayIt();
let b2 = new B();
b2.sayIt();
关于javascript - es6 从静态函数访问类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40765805/