17-07-2010

Javascript Singleton examples in JavaScript

In OOP the singleton is basically a class which restricts it's instantiation to one object. This is useful for when only a single object is needed to maintain a certain functionality or global state available throughout a complex system.

In JavaScript the singleton serves first and foremost as a namespace provider to isolate implementation code from the global namespace and providing a single point of access for functionalities.

The JavaScript Singleton can take several different forms each providing different possibilities and limitations. Below are examples of the two most commonly used singleton structures.

In it's simplest form the JavaScript is simply an object literal grouping together related methods and properties:

var mySingleton = {
	property1:"bleh",
	method1:function(){
		alert('mop');
	}
}

The following structure alows the singleton to have private members and methods by encapsulating variable and function declarations inside a closure, and exposing only those that are to be publicly accessible.

var mySingleton = function(){
 
	/*private variables and methods (not accessible directly through the  mySingleton namespace): */
 
	var privateVar = 'bla';
	function alertPrivate(){
		alert(privateVar);
	}
 
	/* public variables and methods (can access private vars and methods ) */
	return {
		publicMethod:function(){
			alertPrivate();
		},
		publicVar:'this is publicly accessible'
	}
}
 
var single = mySingleton();
single.publicMethod();  // alerts 'bla'
alert(single.publicVar); // alerts 'this is publicly accessible'

It is possible to put parentheses around this structure to instantiate it immedeatly after it's parsed.This way it's always present when the script is executed and doesn't have to be instantiated separately.

var mySingleton = (function(){
 
	/*private variables and methods (not accessible directly through the  mySingleton namespace): */
 
	var privateVar = 'bla';
	function alertPrivate(){
		alert(privateVar);
	}
 
	/* public variables and methods (can access private vars and methods ) */
	return {
		publicMethod:function(){
			alertPrivate();
		},
		publicVar:'this is publicly accessible'
	}
})()
 
mySingleton.publicMethod();

If you want to save resources and instantiate the singleton only when it's needed you can put it's instantiation code inside another constructor function like in this example:

var Singleton =(function(){
	var instantiated;
	function init (){
		// all singleton code goes here
		return {
			publicWhatever:function(){
				alert('whatever')
			},
			publicProperty:2
		}
	}
 
	return {
		getInstance :function(){
			if (!instantiated){
				instantiated = init();
			}
			return instantiated; 
		}
	}
})()
 
//to call public methods now use:
Singleton.getInstance().publicWhatever();

Comments:

3 comments.
Your comment:

»
Danjah 14/12/2010, 10:37 am
I'd used all but the last, thanks for that suggestion - easy enough to integrate into what I've got.
Tester 05/07/2011, 6:27 pm
If I copy&paste the last example, I get a

"Singleton.getInstance.publicWhatever is not a function"

Whats the issue?
pipo de clown 18/07/2011, 2:12 pm
It should say Singleton.getInstance().publicWhatever();

 

[x]