Alternatives to singletons in javascript

Singletons are quite popular on this blog. A lot of people are coming here from that search. In a sense, I’m happy to have such a considerable traffic from google. On the other hand, I’m not proud that this post is my most popular. Why? Because I don’t believe in singletons in javascript. This concept belongs to more object-oriented languages, even though we can have an half-baked OO in javascript. Singletons are just too much of a hassle compared to a simpler solution.

What is a singleton?

A singleton is a design pattern. When instanciating a singleton class, it will always return the same instance of the class. You can’t create more than one instance of the class no matter how many time you call the “new” operator.

Some people think that singleton shouldn’t be a pattern. Personally, I never use it in javascript because they are not “javascript-friendly” (in fact, the whole concept of OO is not javascript-friendly). Here’s what I do.

The alternatives

Just between you and me, when we want to use a singleton, it’s probably because we want to encapsulate a certain part of the code to be easier to read and understand.

Alternative #1 : simple and clean

The easiest way of encapsulating functionalities is to create an object. Sure, it’s “untyped” but types don’t mean a lot in a dynamic languge like javascript. You have to learn to work with it. Here’s how I do it (view on github).

Alternative #2 : more complex

Let’s say you have a big project and you want to really separate every functionalities in “namespaces”, it would be easier to use a more complex technique.

You can take a look at jsKata where every library I wrote has its own namespace (jsKata.undo or jsKata.timezone). jQuery is also using this technique (source code).

Let’s say you have a 2 levels deep namespace but you use the alternative #1 as described ealier. You would end up with this (view on github).

As you can see at line #6, the reference to your msg variable is pretty long. If you have a lot of code, it would become redundant.

If you want to keep your code readable, it’s a good idea to use a self-invoking function like this (see on github).

Let’s study it line by line.

var instance = (function() {
//… code is here…
})();

This is the self-invoking part of the technique. You see that function(){} is in parenthesis. So the result of the parenthesis is a function object (and not the result of the function). After these parenthesis, there’s an empty set of parenthesis. It means that the object function in parenthesis is called.

var i = {
// … more code …
}

This creates a scope. At this moment, the i variable is used as a shorthand for myApplication.instance.

hello : function() {
alert(i.msg);
}

As you can see, we can use i in the hello function to get the msg variable.

return i;

Finally, by returning i as the result of the function call, it gets assigned to myApplication.instance.

No more singletons please

When you know these techniques, I can’t see any reason of using singletons anymore. Forget about using javascript as if it was a complete object-oriented language and start using it as it is.

  • http://topsy.com/www.javascriptkata.com/2010/10/20/alternatives-to-singletons-in-javascript/?utm_source=pingback&utm_campaign=L2 Tweets that mention Alternatives to singletons in javascript » Javascript Kata — Topsy.com

    [...] This post was mentioned on Twitter by Andrés Nieto and nachaos, ajcuellar. ajcuellar said: RT @aNieto2k: http://kcy.me/h87 <– Alternativas a #singletons en #javascript [...]

  • stiggg

    Why do you think javascript is not a complete object-oriented language?

  • http://www.javascriptkata.com dsimard

    To be considered fully OO, a language has to respect some “features” like inheritance and polymorphism (http://en.wikipedia.org/wiki/Object-oriented_programming). Javascript can have a kind of inheritance but it's not strict inheritance. It's more like an “extension” of another object, the way mixins work (http://en.wikipedia.org/wiki/Mixin). From wikipedia : “Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality”.

    I'm thinking about writing a post about it soon… stay connected!

  • crashandburn

    how about this:
    (
    var instance;
    Singleton = function Singleton() {

    if (!instance) {
    instance = new Singleton();
    }
    return instance;
    }
    )()

  • indieinvader

    JavaScript's OO (Prototypal Inheritance) is superior to “Classical” Inheritance because you can implement “Classical” Inheritance using using JavaScript and Prototypal patterns.

    See: http://javascript.crockford.com/inheritance.html and http://javascript.crockford.com/prototypal.html

  • http://twitter.com/rmanalan rmanalan

    I'm confused… isn't your self-invoking function example a singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern#Implementation_2)? I've gotten into the habit of using the revealing module pattern for the past several years -> http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing.

  • bentruyman

    I've always called this pattern an object literal singleton. Sure, you might not my instantiating it with the `new` keyword but I still consider what you're doing a singleton.

  • http://www.javascriptkata.com dsimard

    yes… this is why it's an alternative to the classical singleton with instantiation…

  • bentruyman

    Sorry. I guess where I got confused was that, already, many JavaScript devs are writing our singletons like this. I know I have for the past few years. And when I saw the title of the article, I thought this was going to be a new pattern.

  • http://www.javascriptkata.com dsimard

    absolutely not… it's just that there are *a lot* of developers who are still using the classical oo-style singleton with instanciation and all. This post aimed at them. There's also a lot of people who are coming here when searching for “javascript singleton” and I wanted to write about the “right” way to do it.

  • http://twitter.com/tbreisacher Tyler Breisacher

    Personally, I would be inclined to do this, which makes 'msg' a “private” variable — only accessible by functions inside the self-executing function and completely inaccessible elsewhere.

    myApplication.instance = (function() {
    var i = {};
    var msg = “Hello world!”;
    i.hello = function hello() {
    alert(msg);
    };

    return i;
    })();

    Hooray closures.

  • http://www.facebook.com/people/Rankertestabc-Rankertest/100001433863715 Rankertestabc Rankertest

    “Singletons are just too much of a hassle compared to a simpler solution.”

    Are you kidding me?? your solution is convoluted and unnecessary for most types of code.

    There is nothing wrong with a singleton if the application of it fits the need. What you are suggesting is harder to maintain, and more difficult to read. This doesn't really help anyone.

    If your requirements demand an OO codebase, then your design pattern should reflect that – but to say that all singletons are bad (a hassle?), is just plain false.

  • http://www.javascriptkata.com/2007/04/04/how-to-make-a-singleton/ How to make a singleton in javascript » Javascript Kata

    [...] How to make a singleton in javascript Posted on April 4, 2007, 9:53 am, by dsimard, under black belt, object-oriented. [UPDATE : This post is outdated. Check out the new post on singletons.] [...]

  • http://www.javascriptkata.com/2009/09/30/how-to-write-a-singleton-class-in-javascript/ How to write a singleton class in javascript » Javascript Kata

    [...] How to write a singleton class in javascript Posted on September 30, 2009, 7:59 am, by dsimard, under black belt, function, object-oriented. [UPDATE : This post is outdated. Check out the new post on singletons.] [...]

  • http://vilumparminavilumn.com/ Parminavilum

    Blogs ou should be reading…

    [...]Here is a Great Blog You Might Find Interesting that we Encourage You[...]……

  • http://en.wikistance.org/index.php/User_talk:Hardsi1708 check this

    Recent Blogroll Additions……

    [...]usually posts some very interesting stuff like this. If you’re new to this site[...]……

  • Orkje

    On the other hand, the fact that you can’t have classes and private or protected variables makes javascript VERY non-OO.