Object-Oriented JavaScript Tip: Implementing the Singleton Pattern
The Singleton design pattern is a development approach that ensures only a single instance of a particular class is available in a system. Imagine building the game of chess, you would only want there to be one instance of the board floating around—say an instance of a class called ChessBoard. The Singleton pattern ensures that there will only ever be one ChessBoard object available in your game.
Often the implementation of a Singleton looks something like this:
function Singleton() { } Singleton.getInstance = function( ) { if (Singleton.instance == undefined) Singleton.instance = new Singleton(); return Singleton.instance; }
However, this is a port to JavaScript from other languages and it doesn’t offer a very robust implementation of the Singleton. For example, this design relies on calling Singleton.getInstance() to retrieve the single instance. However, nothing prevents calling…
var instance1 = new Singleton(); var instance2 = new Singleton(); alert( instance1 == instance2 ); // outputs false because these are two object instances
…to create two instances, defeating the pattern. A better approach is to encapsulate the Singleton constructor function in a variable and return a reference to the function rather than the instance, and then provide access to the instance via a getInstance method as above.
var Singleton = new function Singleton() { var instance = this; Singleton.getInstance = function() { return instance; } }
In this case, the code shown earlier does not break the pattern:
var instance1 = new Singleton(); var instance2 = new Singleton(); alert( instance1 == instance2 ); // outputs true because these refer to the same constructor function
However, this just prevents circumvention of the pattern, the same object instance has not yet been retrieved. To do this the static getInstance() method is called on the constructor reference variable.
var instance1 = Singleton.getInstance(); var instance2 = Singleton.getInstance(); alert( instance1 == instance2 ); // outputs true because these refer to the same object instance
Additionally, a toString method, as well as static and instance methods (though both are functionally identically in this case since there’s only one instance available) can be built into the Singleton definition, like so:
var Singleton = new function Singleton() { var instance = this; Singleton.getInstance = function() { return instance; } this.toString = function() { return "[object Singleton]"; } this.instanceMethod = function() { alert( "instance method called!" ); } Singleton.staticMethod = function() { alert( "static method called!" ); } return Singleton; }
Try these out:
Singleton.staticMethod(); Singleton.getInstance().instanceMethod();
Since JavaScript is a prototype-based language (not actually having classes), additional functionality can be added through the Singleton’s prototype, as in:
Singleton.prototype.custFunct = function(){ alert( "A custom method" ); } // add instance method Singleton.getInstance().custFunct(); // call new instance method

November 23rd, 2009 at 3:22 pm
in the line “var Singleton = new function Singleton() ”
when Singleton.getInstance is called, is the variable or function Singleton being dereferenced?
November 23rd, 2009 at 4:00 pm
Hi Daniel,
If I understand the question correctly, it’s the variable. Notice “new Singleton();” and “Singleton.getInstance();” won’t work if the variable name is changed, however, they don’t care if the constructor function name is changed (as long as it is consistent within the function definition itself).
March 28th, 2010 at 3:15 am
It bothers me that (Class.Singleton() !== (new Class())) so I figured out how to stop instantiation of the class without disrupting the way it works… here it is:
March 28th, 2010 at 11:01 am
Why not just using
When the code run, the Singleton is automatically instantied an could not be instantied a second time
(except if used with var Second = new Singleton.constructor())
}();
January 24th, 2011 at 6:43 am
“no need for a class-like constructor for an object.
object literals is all you need.”
Douglas CrockFord,
senior JavaScript architect
February 3rd, 2011 at 1:23 pm
I like being able to include private vars, I prefer the named object signature for singletons sometimes.
July 26th, 2011 at 9:23 am
I found a bug on it….
var Teste = new function Teste()
{
var instance = this;
Teste.getInstance = function()
{
return instance;
};
this.texto = “Texto”;
return Teste;
};
var x = Teste.getInstance();
x.texto = “Testando”;
var t = new Teste();
var y = t.getInstance();
console.log( x == y );
It will return false…..
x.texto = Testando
y.texto = Teste
Can I somehow fix it?
July 26th, 2011 at 9:43 am
Hi Rafael,
This code doesn’t prevent you from creating multiple instances of the singleton if you want to, it just provides a pattern to avoid doing that. In your code you have:
var x = Teste.getInstance();…and…
var t = new Teste();Which means
var xandvar tare now two different instances, making your comparison equalfalse. Also, you have the code:var y = t.getInstance();…which won’t do, as you are trying to access a method
getInstance()on theTesteobject assigned tot. The objecttdoes not have that method as thegetInstance()method is a static method attached to the classTeste, not an instance of that class. So to fix this, you’d need to eliminatevar tand changevar yto:var y = Teste.getInstance();July 26th, 2011 at 9:47 am
I understood, I just though that this could be fixed in the function, thx for the help.
Explaning, I’m trying to find a Singleton that won’t have multiple instances, even if the “user” try to hack it.
July 26th, 2011 at 9:56 am
Hi Rafael,
Off the top of my head you could have this:
var instance;
var Teste = new function Teste()
{
if (!instance) instance = this;
Teste.getInstance = function()
{
return instance;
};
this.getInstance = function()
{
return instance;
};
this.texto = "Texto";
return Teste;
};
Which would work with the rest of your code. It’s not so self-contained though.
July 26th, 2011 at 11:14 am
I found a way to do it…
var Teste = (function()
{
var instance = null;
var TesteClass = function()
{
this.texto = “texto”;
};
return new function()
{
this.getInstance = function()
{
if (instance == null)
instance = new TesteClass();
return instance;
};
};
})();
var t = Teste.getInstance();
console.log(“t: ” + t.texto);
t.texto = “Testando”;
var x = Teste.getInstance();
console.log(“x: ” + x.texto);
It works, and I can’t call “new Teste()”, it returns an error.
July 26th, 2011 at 11:36 am
Nice work! Thanks for sharing.