Aug 06 2009
Singleton in 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 ![]()

-
Jani Hartikainen



