javascript - How to create singleton classes in Javascript?
问题描述
I am working on a large project where I have multiple managers to handle different tasks, I need an only a single object of these managers to be created when I start the app,
I came across this method of Singleton creation
class QuestionnaireManager {
constructor() {
if (this.instance) {
return;
}
this.instance = this;
}
}
Is this an acceptable way, is there any downside, I am coming from JAVA
Kotlin
background and this seems to simple to be true where we have so much to deal in case of singletons in other languages. (Most of those cases have to deal with multi-threading but as JS is single-threaded so I think this would be sufficient way)
Still need opinion on best practices, or any other Dependency Injection methods where we don't even rely on Singleton but create the object once and reuse all over the project with dependency injections.
I would like to know the opinion of sensie in JS.
解决方案
这不是在 ES6 中实现 Singleton 的正确方法。正确的方法:
class QuestionnaireManager {
constructor() {
if (QuestionnaireManager._instance) {
throw new Error("Singleton classes can't be instantiated more than once.")
}
QuestionnaireManager._instance = this;
// ... your rest of the constructor code goes after this
}
}
var managerOne = new QuestionnaireManager()
var managerTwo = new QuestionnaireManager() // Throws error
或者,如果您不希望在创建第二个实例时引发错误,您可以只返回最后一个实例,如下所示:
class QuestionnaireManager {
constructor() {
if (QuestionnaireManager._instance) {
return QuestionnaireManager._instance
}
QuestionnaireManager._instance = this;
// ... your rest of the constructor code goes after this
}
}
var managerOne = new QuestionnaireManager()
var managerTwo = new QuestionnaireManager()
console.log(managerOne === managerTwo) // logs "true"
推荐阅读
- ios - 如何修复 2 个 ViewController 之间的通过日期
- javascript - Android webview 中的 JavaScript 注入
- spring - 在条件 Bean 上使用 @Value
- typescript - 打字稿检查对象是否匹配类型
- java - 阻止 Spring Boot 应用程序关闭,直到所有当前请求都完成
- angular - Angular 找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays
- peoplesoft - PeopleSoft App Engine 程序流程如何发生
- mathematical-optimization - 有没有办法在 LpSolve 中添加像 x(y+z)<0 这样的约束?
- git - git相同的文件,该文件中的不同内容git合并时会发生什么
- java - 使用 Java Builder 设置 eclipse-error