Singleton Pattern in Javascript

27-01-2018 • Javascript Patterns

In javascript we can write Singletons in a few different ways, here are my personal es5, es6 and es7 favorites.

es5

var Singleton = (function() {
  var instance = null

  function Singleton(){
    if (!instance) {
      instance = this
      // constructor function code goed here
    }
    return instance
  }

  return Singleton
})()

We first check if instance was already set, if not we set the instance variable to reference this we then continue with the constructor function and return instance. The next time we create a new object, instance is already set, so it will skip the code in the constructor function and will just return instance with references the first created instance. By using a iife (immediately invoked function expression), we ensure that instance can't be accessed by code other then the Singleton.

es6

let instance = null

export default class Singleton {
  constructor() {
    if (!instance){
      instance = this
      // constructor function code goed here
    }
    return instance
  }
}

Basically the same idea as the es5 version, but this time we use modules to we ensure that instance can't be accessed by code other then the Singleton. For this to work we need to put the Singleton in it own file and import it like so:

import Singleton from './path/to/Singleton.js'

es7

class Singleton {

  static instance = null

  constructor() {
    if (!Singleton.instance){
      Singleton.instance = this
      // constructor function code goed here
    }
    return Singleton.instance
  }
}

Again this is same idea as the es5 version, but this time we use a es7 static property to store the instance. Static properties are defined on the class and not the instances, therefore the instance property will be the same for all instances.