JavaScript: three implementations of the Singleton Design Pattern

JavaScript: three implementations of the Singleton Design Pattern

Three ways of implementing the Singleton Design Pattern in JavaScript.

In this article I'd like to present three ways of implementing the Singleton Design Pattern in JavaScript. The preferred choice is entirely up to you, depending on your needs and the requirements of your code.

Object literal

This is the most straightforward implementation of this pattern:

var Singleton = {

	test: function() {
	
		var member = 'Test';
		
		alert(member);
	
	}
};

Singleton.test(); // Test

Self-instantiating object

In this case the new operator automatically creates a single instance of an object:

var Singleton = new function() {

	var member = 'Test';
	
	this.test = function() {
	
		alert(member);
	
	}

}();

Singleton.test(); // Test

Self-executing function

A self-executing function is defined by making it return an object which contains a getter for the unique instance of the object. Note how the constructor property of the object is hidden after the instantiation to make sure that only a single instance of the object is returned.

​var Singleton = (function() {
    
    function Singleton() {
        var member = 'Test';
        this.test = function() {

               alert(member);
            
        }
    
    }
    var instance;
    return {
        getInstance: function(){
            if (instance == null) {
                instance = new Singleton();
                instance.constructor = null;
            }
            return instance;
        }
   };
})();

var mySingleton = Singleton.getInstance();
mySingleton.test(); // Test