How to write a singleton class in javascript
If I look at my stats, a lot of people are wondering how to write a singleton class. I already wrote about it before but my old solution exposed the instance of the class so more than one instance could be created thus making it not completly a singleton class.
Here’s the new solution using a private variable for the instance.
-
function Cats() {
-
var names = [];
-
-
this.singletonInstance = null;
-
-
// Get the instance of the Cats class
-
// If there’s none, instanciate one
-
var getInstance = function() {
-
if (!this.singletonInstance) {
-
this.singletonInstance = createInstance();
-
}
-
return this.singletonInstance;
-
}
-
-
// Create an instance of the Cats class
-
var createInstance = function() {
-
// Here, you return all public methods and variables
-
return {
-
add : function(name) {
-
names.push(name);
-
return this.names();
-
},
-
names : function() {
-
return names;
-
}
-
}
-
}
-
-
return getInstance();
-
}
How to use it
-
function run() {
-
// Add a new cat
-
var cat1 = new Cats();
-
cat1.add("Mistigri");
-
jsKataEx.assert(cat1.names().length == 1, "cat1 contains 1 cat : " + cat1.names().toString());
-
-
// Use another instance
-
var cat2 = new Cats();
-
jsKataEx.assert(cat2.names().length == 1, "cat2 contains Mistigri added in cat1 : " + cat2.names().toString());
-
-
// Add another cat in the other instance
-
cat2.add("Felix");
-
jsKataEx.assert(cat2.names().length == 2, "cat2 contains Mistigri and Felix" + cat2.names().toString());
-
jsKataEx.assert(cat2.names().length == 2, "cat1 also contains Mistigri and Felix" + cat1.names().toString());
-
}
Get the code on GitHub and see it live in action.


very cool & good tip, thank you very much for sharing.
Can I share this snippet on my JavaScript library?
Awaiting your response. Thank
[...] How to make a singleton in javascript April 4, 2007 by Dan Simard black belt, object-oriented | 23 comments [UPDATE : This post is outdated. Check out the new post on singletons.] [...]
Could you explain how this is supposed to be used?
This doesn’t do much:
var foo = new Cats();
var bar = new Cats();
foo.add(”Joe”);
bar.add(”Bert”);
foo.names() // => ["Joe"]
Cheers.
You could rewrite this (for more efficiency):
function Cats(){
var names = [],
proto = arguments.callee.prototype;
if (!proto._initiated){
proto.add = function(name) {
names.push(name);
return this.names();
};
proto.names = function() {
return names;
};
proto._initiated = true;
}
return this;
}