The Linux Page

Singleton in JavaScript (ES6+)

A Single Poppy in a field.

There is an old book about design patterns in JavaScript and there is an example of the Singleton pattern:

https://addyosmani.com/resources/essentialjsdesignpatterns/book/

However, the new way of creating a Singleton in ES6 uses a simple class and exports the instance as follow:

class Singleton {
  constructor () {
    if (!Singleton.instance) {
      Singleton.instance = this
    }
    // Initialize object
    return Singleton.instance
  }
  // Properties & Methods
}

const instance = new Singleton()
Object.freeze(instance)

export default instance

Source: https://stackoverflow.com/questions/1479319#46184368

However, the example above assumes that the new would happen multiple times, which is not possible in an Node.js module. So you do not need to complicated handling of the instance as shown above. The following will be good enough:

class Singleton {
  constructor () {
  }
  // Properties & Methods
}

const instance = new Singleton()
Object.freeze(instance)

export default instance

Note that you share the instance, not the class so no one can just create another instance (well, okay, the instance does expose the constructor and you could have some sneaky bastard do such a thing, but I don't think it's likely at all...)