【发布时间】:2018-09-25 13:17:10
【问题描述】:
我正在尝试在 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(); -
javascript中的单例称为object。
-
我不想使用 new 关键字,这就是为什么如果使用“new”调用构造函数,我会在构造函数中抛出错误。 @乔纳斯W。是的,我知道,最简单的单例就是简单的 JS 对象 {}。我想使用 ES6 类。
-
只是不要导出类。只导出你想要的
getInstance()函数。或者,也许更好,只是创建和导出单例,仅此而已。即使您没有导出类本身,一个调用仍会调用单例上的所有方法。 -
I don't want to use new keyword,然后只导出一个对象而不是类。export new TestClass(),如果你这样做是为了惰性构造,那么导出一个包装函数来导出对象。
标签: javascript constructor ecmascript-6 singleton es6-class