What is a singleton?

I’ve made this page because I’m often asked the question “what is a singleton” by those approaching Javascript as their first programming language. Hopefully this will clear, rather than muddy, the waters.

Singleton is a term taken from traditional (classical) Object Oriented Programming, where there are two basic types of classes: singletons and instantiable.

Instantiable classes in traditional OOP are templates for object instances. Let’s say you define an instantiable class Cat which starts running in a random direction:

var Cat = function(name){
    this.name = name;
    var random = Math.floor(Math.random() * 4) + 1; //1-4
    this.directionRunning = ['north', 'east', 'south', 'west'][random];
Cat.prototype.changeDirection = function(direction){
    this.directionRunning = direction;
var cats = [];
cats.push( new Cat('Fluffy') );
cats.push( new Cat('Spike') );
cats.push( new Cat('Preia') );
cats.push( new Cat('Killer') );
cats.push( new Cat('Ginger') );

(Note: this isn’t how I recommend writing your instantiable classes in Javascript! It’s just the way that most people understand, so I chose it for this explanation of singletons.)

We now have five cats running in random directions. What we need is a cat herder (also known as a manager) to get them in order! This is where the singleton comes in — we only need one cat herder for our application/page.

var catHerder = {
    cats: window.cats,
    herd: function(direction){
        for (var i=0, l=this.cats.length; i<l; i++) {

Now our singleton object, the cat herder (or cat manager) has rounded them all up and sent them heading south!

Note that our herder didn’t need instantiating. It can be used in place. That’s what makes it a singleton.

One thought on “What is a singleton?

  1. Pingback: Caveats of the JS Module Pattern « Javascript Voodoo Sanity Check

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>