首页 > 解决方案 > 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.

标签: javascriptreactjssingleton

解决方案


这不是在 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"


推荐阅读