RSS Feed

JavaScript Singleton Design Pattern Demystified

February 7, 2011 by Dusan Gledovic

Singleton is one of the creational design patterns. It serve purpose of “restricting the instantiation of a class to one object”. (wikipedia)

Because of its nature, JavaScript has different way of implementation of the Singleton Pattern than “traditional” object-oriented languages like Java, C#, PHP etc.

To get proper Singleton implementation (in JavaScript) we have to fulfill following demands:

  • once instantiated, attempt to instantiate same class again should actually return the first object
  • instance should not be rewritable
function Test() {
	// private
	var instance = this;

	// rest of the code

	// overwriting itself (constructor) from global space
	// so that following calls to new Test();
	// actually returns private variable instance
	Test = function () {
		return instance;
	};
}

obj1 = new Test();
obj2 = new Test();

obj1 === obj2 // result: true

This pattern uses power of closures to preserve global namespace from cluttering and instance from being overridden from that same space, the global one.

In above primer we have Test class. In it there is instantiated variable instance with var keyword so that it becomes private variable. Then this is assigned to it so that it could be called from inner functions and most of all inner Test function which will override its parent Test (because of the same name) constructor from global namespace once the parent gets instantiated.

That’s the reason obj1 and obj2 identity comparison returns true, because second call new Test() actually just returns instance variable. Keeping in mind that objects are passed by reference in JavaScript, it’s obvious that obj1 and obj2 are just different name pointing to the same address in memory.

function Test() {
	// private
	var instance = this;

	// rest of the code
	// ...

	// private
	var oneVeryImportanFunction = function(){
		alert(typeof instance);
	}

	// public
	this.getType = function(){
            oneVeryImportanFunction();
	}

	// overwriting itself (constructor) from global space
	// so that following calls to new Test();
	// actually return private variable instance
	Test = function () {
		return instance;
	};
}

obj1 = new Test();
obj2 = new Test();

obj1 === obj2;

obj2.getType();

Usually, “By convention, we make a private that” = this ” variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.” crockford , but here in oneVeryImportanFunction() function we could use instance variable as it serves same thing like that, but it has different name.


2 Comments »

  1. Werbeagentur says:

    I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.Any way Ill be subscribing to your feed and I hope you post again soon

  2. I am really satisfied with this posting that you have given us. This is really a stupendous work done by you. Thank you and looking for more posts by you.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>