Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 262
Divyanshu Negi Avatar asked Aug 24 '26 11:08

Divyanshu Negi


2 Answers

That ain't the right way to implement Singleton in ES6. The correct way:

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

Or, if you don't want an error to be thrown on second instance creation you can just return the last instance, like so:

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"
like image 116
UtkarshPramodGupta Avatar answered Aug 26 '26 00:08

UtkarshPramodGupta


// Singleton.js

class Singleton {
    constructor(){
        if(Singleton._instance){
            console.warn("already created!");
            return Singleton._instance;
        }

        Singleton._instance = this;

        console.log("singleton created");

        this._createdTime = new Date();
    }

    static instance() {
        if(!Singleton._instance){
            return new Singleton();
        }

        return Singleton._instance;
    }

    createdTime() {
        return this._createdTime.toISOString();
    }
}

Singleton._instance = null;

export default Singleton;

// main.js

import Singleton from "./Singleton"

const a = new Singleton();
const b = new Singleton();
const c = Singleton.instance();

console.log(a.createdTime());
console.log(b.createdTime());
console.log(c.createdTime());

Output would be enter image description here

like image 29
ZhefengJin Avatar answered Aug 25 '26 23:08

ZhefengJin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!