Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Aug 06 2009

Singleton in Javascript

Published by at 7:14 pm under JavaScript

If you are familiar with design patterns then, you may also know about Singleton Pattern. It is used to restrict creation of multiple instance of a class or a class will have only one instance.

function MyClass()	{
	if (MyClass.caller.toString() != MyClass.getInstance)	{
		throw new Error("Initialization not allowed");
	}
	this.someProperty = "some value";
}
MyClass._instance = null;
MyClass.getInstance = function()	{
	if (MyClass._instance == null)
		this._instance = new MyClass();
	return this._instance;
}

var c = MyClass.getInstance();

fireunit.compare("some value", c.someProperty, "this should pass");
c.someProperty = "aa";
//try to create another instance
var d = MyClass.getInstance();
fireunit.compare("aa", d.someProperty, "new value - this should pass");
fireunit.testDone();

Here is the output of the code:

Hope this will help you :)


3 responses so far

3 Responses to “Singleton in Javascript”

  1. Jani Hartikainenon 07 Aug 2009 at 5:59 pm

    Interesting trick. Wouldn't have thought of it myself!

  2. Jani Hartikainenon 07 Aug 2009 at 10:59 pm

    Interesting trick. Wouldn't have thought of it myself!

  3. Prefab Homeson 22 Feb 2011 at 5:13 am

    Thank you for this great idea!

RSS Feed
Subscribe by email
Follow me @ Twitter