JavaScript Singleton Design Pattern

javascript-singleton-pattern
JavaScript Singleton pattern ensure that only a single instance of the class may exits in application. Details of singleton design pattern can be found in the an existing post named Java Singleton Design Pattern Tutorial. This pattern comes in handy when you want to create a class whose functionality doesn’t change for its multiple instances for e.g. an Ajax handler or Util class.

Implementing Singleton in JavaScript

Implementing a basic singleton pattern can be as simple as creating a simple object literal, because the created object will be an instance itself:

var Sun = {
  publicEmitLight:function() {// do something to emit light
                  },
  mass: 10000
};

The above approach is easy to implement, but is very limited in usage. For example, it is not possible to have private members in this object.

To create a more usable Singleton object, it will be required to create a class and then expose a method in the class which always returns the same instance. To do so, this exposed method would check if the instance is already created, and if so return it, else it would create one before returning.
Ok, let’s try to put above lines into a JavaScript code. Creating the Sun of our Solar System again with some private members this time:

var Sun = (function(){
              var sunInstance; //private variable to hold the 
							   //only instance of Sun that will exits.

              var createSun = function(){
                         var privateMass = 10000000000; //private
                         var looseMass = function(mass){
                             privateMass -= mass;    
                         }
                         var publicEmitLight = function(){
                                  //some complex Nuclear fission 
								  //calling looseMass()
                                  looseMass(10);
                         };
                         var getMass = function(){
                                  return privateMass;
                         };
                         return {
                                emitLight: publicEmitLight,
                                getMass: getMass
                         };
              };

              return {
                    getInstance: function(){
                          if(!sunInstance){
                              sunInstance = createSun(); 
                          }
                          return sunInstance; 
                    }
              };
})();

Lets break down above code to understand whats going on here. We created a variable Sun, and instantiated it using JavaScript Module Pattern. But instead of exposing declared members, we returned a new property getInstance(). Lets re-look the return statement:

return {
                    getInstance: function(){
                          if(!sunInstance){
                              sunInstance = createSun(); 
                          }
                          return sunInstance; 
                    }
              };

The Sun variable will be assigned what this return statement evaluates to. And clearly, this evaluate to an object with only one property of type function: getInstance. So whenever we need to obtain an instance of sun in our code, all we do is use:

var mySun = Sun.getInstance();

In above line, we executed the only public method in Sun module: getInstance(). Inside the getInstance() function we check if the local private variable sunInstance exists, if not this is assigned a value by calling a private function createSun(). And at last, getInstance() return this private variable sunInstance. So it is getInstance() which ensures if the sun doesn’t exists it creates one before returning. And always returns the same instance of Sun. This is because sunInstance is inside a closure and will always be the same instance between many calls.

Ok, next step is to find out how does createSun() works. Lets go though the code of createSun():

var createSun = function(){
					var privateMass = 10000000000; //private
					var looseMass = function(mass){
					 privateMass -= mass;    
					}
					var publicEmitLight = function(){
						  //some complex Nuclear fission 
						  //calling looseMass()
						  looseMass(10);
					};
					var getMass = function(){
						  return privateMass;
					};
					return {
						emitLight: publicEmitLight,
						getMass: getMass
					};
				};

This is the function where all the private and public property of Sun are implemented. This function returns an object with properties ’emitLight’ and ‘getMass’. Note, that the members privateMass, looseMass(), publicEmitLight() and getMass() will continue to exist after call is complete due to closure. Calling createSun() will always return a new object with property ’emitLight’. So it needs to be ensured that createSun() is called just once, and obtained instance is to be stored and returned on further request to get instance of Sun. This instance is store in the private variable ‘sunInstance’ and any call to getInstance() first checks whether sunInstance is already defined or not, as we saw above in getInstance() implementation.

Lets put above implementation to test:

var sunA = Sun.getInstance();
var sunB = Sun.getInstance();
console.log(sunA === sunB); //true
sunB.emitLight(); //loose some Mass in sunB
var massInSunA = sunA.getMass();
var massInSunB = sunB.getMass();
console.log(massInSunA === massInSunB); //true

Output:

true
true

It is worth noting that the popular Module pattern is also a type of Singleton pattern, although it doesn't expose a getInstance() method to get instance of Singleton object which is considered to be a signature method in Singleton pattern.

The End :)

Get our Articles via Email. Enter your email address.

You may also like...

3 Comments

  1. Abhishek says:

    Thanks a lot. Nice explanation of Singleton in JavaScript

  2. sbking says:

    “The above approach is easy to implement, but is very limited in usage. For example, it is not possible to have private members in this object. To create a more usable Singleton object, it will be required to create a class and then expose a method in the class which always returns the same instance.”

    No, that’s simply wrong… Consider this:

    var singleton = (function() {
      var privateData = "foo"
      var privilegedMethod = function() {
        return privateData;
      };
    
      var why = {
        not: "just",
        create: "a",
        literal: "object",
        with: privilegedMethod
      };
    
      return why;
    }());
    
    console.log(singleton.privateData); // => undefined
    console.log(singleton.with()); // => "foo"
    
    • sbking says:

      I just read the end where you acknowledge this pattern:

      “It is worth noting that the popular Module pattern is also a type of Singleton pattern, although it doesn’t expose a getInstance() method to get instance of Singleton object which is considered to be a signature method in Singleton pattern.”

      Here’s the thing: the popular Singleton pattern is a hack around class-based object systems. The mere phrase “Singleton class” is an oxymoron. There is no reason to have a `getInstance()` method for a JavaScript singleton – with prototype inheritance, literal objects, and IIFE closures, *we really don’t need to emulate classes*. Prototypes are more expressive and powerful.

Leave a Reply

Your email address will not be published. Required fields are marked *