How to make a singleton in javascript
Singleton is one of the most common and easiest design pattern. In fact, a lot of designs are wrong just because the developer didn’t know about singletons and design patterns (I could have said : a lot of my designs were wrong just because I didn’t know about singletons and design patterns).
I was looking at the first three results for singleton javascript on Google and I was more than deceived by what they had to tell us. That’s why I write this article.
What is a singleton class?
A singleton is when your application needs to use just one instance of an object to centralize your access to it. Example, I have a list of cat names that can be used in various functions of an application. Sometimes, names are added or removed. I could use a global variable to the page containing the list. The problems are :
- It’s a global variable (global variables are bad).
- I don’t know when the list is created or initialized.
- If you reuse your class in another project, you will always need to define a global variable and instance it correctly.
- It’s ugly.
If I use a singleton pattern, the advantages are :
- The object is always correctly created.
- You don’t have to ask yourself questions about the state of the list or whatever. It just works!
- Another programmer can recognize the singleton pattern thus making it easier for him to work.
How to write a singleton class
Before writing a singleton, you need to know about creating objects and static functions.
-
// I create the class
-
function CatNames() {
-
this.names = new Array(); // The array that will contain the names
-
}
-
-
CatNames.instance = null; // Will contain the one and only instance of the class
-
-
// This function ensures that I always use the same instance of the object
-
CatNames.getInstance = function() {
-
if (CatNames.instance == null) {
-
CatNames.instance = new CatNames();
-
}
-
-
return CatNames.instance;
-
}
-
-
// Function to add a cat name
-
CatNames.prototype.add = function(catName) {
-
this.names.push(catName);
-
}
-
-
// Function to remove the last cat name
-
CatNames.prototype.removeLast = function() {
-
return this.names.pop();
-
}
-
-
// Function to alert all cat names
-
CatNames.prototype.alertAllCats = function() {
-
alert(this.names.join(","));
-
}
I use it in these functions.
-
function addThreeNames() {
-
// I use the one and only instance of the class (the magic of singletons)
-
var names = CatNames.getInstance();
-
-
names.add("Mistigri");
-
names.add("Bibi");
-
names.add("Gary");
-
}
-
-
function removeLastCat() {
-
// Once again, singleton is here
-
var names = CatNames.getInstance();
-
-
names.removeLast();
-
}
-
-
// I call the functions
-
// - no need for a global variable
-
// - no need to create the object and pass it as parameter
-
addThreeNames();
-
removeLastCat();
-
-
// Alert all cats
-
var names = CatNames.getInstance();
-
names.alertAllCats();
The downside of this technique
Yes I know, you can instantiate the singleton class if you want.
-
var catNames = new CatNames();
You know what? You’ll have to follow a simple rule : never instantiate a singleton class. Maybe we could use more techniques that would protect you from instantiating your own singleton class but it would be a waste of time and code.


I think I got a solution to your downside (in fact, I was effectively noting this problem and I thought maybe I had an idea).
Here it is:
———————————
CatNames=new Object();
// This function ensures that I always use the same instance of the object
CatNames.getInstance = function() {
if (CatNames.instance == null) {
// I create the class
CatNamesConstructor = function CatNames() {
this.names = new Array(); // The array that will contain the names
}
// Function to add a cat name
CatNamesConstructor.prototype.add = function(catName) {
this.names.push(catName);
}
// Function to remove the last cat name
CatNamesConstructor.prototype.removeLast = function() {
return this.names.pop();
}
// Function to alert all cat names
CatNamesConstructor.prototype.alertAllCats = function() {
alert(this.names.join(”,”));
}
//CatNames.instance = null; // Will contain the one and only instance of the class
this.instance = new CatNamesConstructor();
}
return CatNames.instance;
}
———————————
This way, since the constructor is private, it is not accessible but the instance property still is (and I haven’t found a way of keeping it private since it doesn’t have any scope or closure). Now, the only way of getting multiple instanciations is to do something like that:
———————————
// Alert all cats
var names = CatNames.getInstance();
names.alertAllCats();
CatNames.instance = null;
var names2=CatNames.getInstance()
names2.alertAllCats();
names.alertAllCats();
———————————
Much less obvious.
Or..
Remembering that prototypes are shared across all instances, why not just keep all shared data in there?
function CatNames() {}
CatNames.prototype = {
names:[],
add:function add() {
return this.names.push.apply(this.names, arguments);
},
removeLast:function removeLast() {
return this.names.pop();
},
log:function() {
var str = this.names.join(”, “);
console.log(str);
return str;
}
};
var x = new CatNames();
var y = new CatNames();
x.add(”Mistigri”);
y.add(”Bibi”);
y.add(”Gary”);
x.removeLast();
alert(x.log() === y.log() && x.log() === “Mistigri, Bibi”);
I find it much more natural since you’re not having to guess whether this object is a singleton or not, just instantiate it and it does all the work for you and works just like you’d want it to (unless one enjoys CatNames.getInstance()).
While x and y share the same stuff, they’re still separate objects that just happen to share the same prototype, so x != y even though they appear that. I don’t find this surprising or troubling, since it seems like ‘new’ should always return a distinct value anyway.
Also, it’s broken if someone changes your prototype, but no one in their right mind changes a prototype of an object without being very comfortable with the consequences.
Of course, I’m left to wonder why you even need a Singleton anyway, but this is the way to do it if you must.
- Aaron
BK, I like the idea and it’s much “cleaner” that way. The problem is that it’s a little too complicated for the real benefits.
“Old” languages (C++, Java) tended to restrict you from doing what you want with your code. Sort of protecting you from yourself.
“New” languages (Ruby, Javascript) let you free of doing what you want. That’s a risk for beginners but that’s salvation for advanced programmers.
Aaron, thanks again for the comment.
That’s a great way of doing a singleton indeed. As you said, the problem could be that you’re calling a “new” instead of the getInstance() function.
Why would we need a singleton anyway? That’s a great question. I’ll make a post about it I guess (if I found a GOOD reason).
Example of a singleton in another world than JS:
I created a project lately that needed a communication layer with a server from a PDA. I wanted the communication layer to be separated from the logic of parsing the data so I did a class for this but I also needed to have a permanent unique connection as connection is almost the longest part of the communication so I did a singleton for that.
Another example for JS this time would be to get a centralized AJAX class that would manage a pool of actions and to them based on a pool of XMLHTTP objects instead of creating new ones each time.
BK: A centralized AJAX class could just be a object literal, right? I don’t see why you need to make the class, then instantiate it.
var AJAXClass = {
doXHR:function(url, options) { … },
sendXHR:function(xhr) { … }
};
AJAXClass.doXHR(”user/add”, { … });
I mean, that works just as well as dropping those functions into a prototype, then adding logic that wraps the Singleton nature of the object, and instantiating it, right?
Aaron and BK : You are both right. It’s just more beginner-friendly to use the BK way of doing it. A lot of people don’t know much about literals (or anonymous objects as I was calling them).
Hi, thanks for the info on the singleton pattern.
I wanted to ask you, so you use any plugin or script to publish
your code. It looks very nice in the syntax highlighted manner.
Please tell me.
Thanks
I use Syntax Highlighter.
I will probably have another version soon for the Singleton pattern…
Hi, singleton are a design pattern i’m using a lot, but here is (imo) a much better way to create the same singleton:
var CatNames = function()
var names = [];
return {
“add”:function(n) { names.push(n); },
“removeLast”: function() { names.pop(); },
“alertAllCats”: function() { alert(names.join(’,'); }
};
{}();
arghh, sorry, misplaced bracket …
var CatNames = function()
{
var names = [];
return {
“add”:function(n) { names.push(n); },
“removeLast”: function() { names.pop(); },
“alertAllCats”: function() { alert(names.join(’,'); }
};
}();
Dan: The apology to Correct Speller wasn’t me. *sigh* Isn’t the internet fun?
Laurent: That’s not a singleton, though. If I understand right, a Singleton’s something that returns a single object despite repeated calls to the constructor. That’s just a private variable through closure. You could attach the object literal to the function itself which would work, like so:
function CatNames() {
if(!CatNames.singleton) {
CatNames.singleton = { /* CatNames initialization here */ };
}
return CatNames.singleton;
}
This is just a more complicated version of a static variable. Again, it seems like, usually, you can boil whatever implementation of singletons down to just using static stuff or prototypes.
The distinction is that they’re lazily loaded which is a definite plus, so if CatNames is expensive to create but you don’t always need it, then you could save yourself some cycles when you don’t call it.
The drawback is that it’s not natural and it’s usually just premature optimization, and since there’s no check of when the object should be destroyed, this giant object (Presumably giant, since you went to the trouble of wrapping it with this) can’t be gc’d for the remainder of the time your page is up.
Steve Yegge rants more about it (alot) here: http://steve.yegge.googlepages.com/singleton-considered-stupid
Aaron : Thanks! I removed the “spell checking” comments because I want comments that are about the subject of the post.
So, I read the article of Steve Yegge and it says a lot about it. In fact, I was recently pushed to singletonize a class and I didn’t do the “getInstance” method but the simpler “static method” and I didn’t understand why should I call a function in two lines instead of one.
var log = Log.getInstance();
log.debug(”This is a debug line”);
instead of
Log.debug(”This is a debug line”);
I could have done
Log.getInstance().debug(”This is a debug line”)
but why??? It’s not as obvious as Log.debug().
The problem with “Design patterns” is that they’re recipes and I tend to use recipes without fully understanding the meaning of it (and I think that a lot of people are also doing this).
Thank!
Singleton is probably the most popular pattern, and at the same time the most ridiculous. A singleton is a way to get global variables in a language, which did everything to avoid it in the first place (The language I’m talking about here is Java). Global variables are bad - even if they have fancy names, like singleton. Just say no, kids.
@troels, this is more and more my point of view on singletons too! Singleton = fancier global. I saw a project in which almost every object was a singleton and it just looked ugly…
BK really needs to use “var CatNamesConstructor = …” so you cannot instantiate CatNamesConstructor in global scope.
Personally, I’ve always preferred:
var CatNames = new function(){
var privateVar;
var privateMethod = function(){
…
};
this.publicMethod = function(){
…
};
};
Notice the “new function(){…}”. Still a little tacky but works quite well.
Dan,
I’m so glad that you have this code blog. I wasn’t able to find exactly what I was looking for, but I definitely got pointed in the right direction. Here’s my implementation of a singleton:
function Singleton() {
if (Singleton.instance == null) {
Singleton.instance = this;
Singleton.instance.initialize();
}
else {
// Do not want the extra object
delete this;
}
return Singleton.instance;
}
Singleton.prototype = {
instance: null,
initialize: function() {
// Actual constructor for your one instance
}
}
This way, I can call new Singleton() and get the same instance, without the need for getInstance().
var instance1 = new Singleton();
var instance2 = new Singleton();
alert(instance1 == instance2); // True
You can ensure no one wipes out your singleton reference by wrapping it all up in a closure:
var MySingleton = (function()
{
var instance = null;
return function()
{
if (instance !== null)
{
return instance;
}
instance = this;
//init code
};
})();
var s1 = new MySingleton();
var s2 = new MySingleton();
s1 === s2; // true
well a very simple way of having singleton is this
Test= function(){
if(!Test.prototype.instance)
Test.prototype.instance=this;
else
return Test.prototype.instance;
}
^^
@zoips @jb
I really like your alternatives. I’ll write a new article with that. Thanks a lot.
A very good and simple article on singleton in JS.
http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html
Hi! I’ve read all your posts and I’m very glad of this discussion. I wonna give something back to all readers and posters in describing a small scenario, where singleton is more than just OOP-Global, and wonna show you, why I think that choosing the right singleton implementation is very important.
I’m deloping a huge project including a JS-Framework. Therefore it’s necessary to inherit classes. So imagine the following example:
We have a class Container and a inherited class FullFadeWindow. The Container-Class represents a Container-Widget that can be instantiated many times and that can contain data loaded per AJAX. The FullFadeWindow is a special window: its always on top and its covering the full screen (or browser window). So I want FullFadeWindow to be a singleton class, inheriting from Container, that is no singleton class.
This can’t be done using a pure static implementation (like Dan’s Log-Example), because of the prototype inheritance. Also the closures-solutions cannot be used this way, because all functions need to be declared in a local context which make prototype inheritance impossible. And because I cannot guarantee that nobody calls my constructor, if I’m using Dan’s first idea, the remaining possibility is MadKat’s one above. This way, we can simple make an existing class to a singleton one, we can use prototype inheritance, and we do not need to “milk” JS to brutally make this object based language to an complete object oriented one.
In addition, the way described in http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html (posted by Antony above) is also not usable in this scenario.
So, if you plan to use prototype inheritance (you know, like X.prototype = new Y()), you should consider MadKat’s solution.
Have fun,
Phil