我正在尝试在JS ES6类中实现单例模式。以下是我目前所写的内容:
let instance;
export class TestClass{
constructor(){
if(new.target){
throw new Error(`Can't create instance of singleton class with new keyword. Use getInstance() static method instead`);
}
}
testMethod(){
console.log('test');
}
static getInstance(){
if(!instance) {
instance = TestClass.constructor();
}
return instance;
}
}
然而,当我调用静态方法
TestClass.getInstance()
时,我得到的不是类对象的实例,而是ƒ anonymous() {
}
我无法访问testMethod函数,但我找不到代码错误 - 非常感谢您的帮助。
instance = new TestClass();
- KeithgetInstance()
函数。或者,更好的方法是创建并导出单例。即使您没有导出类本身,仍然可以通过一个调用在单例上调用所有方法。 - jfriend00export new TestClass()
,如果您是为了懒惰的构造而这样做,请导出一个包装器函数来导出对象。 - Keith