The Hidden Singleton with Javascript

This pattern is well documented else where, I think I first saw it in the Definitive Javascript book. Let's say you want to provide a function that does stuff with a static variable, but don't want that static variable to be global(visible to the outside)? You would do this:

myfunction = function(){
    var mysingleton = new Singleton();
    return function(x, y){
        return mysingleton.doit(x,y);

so now you can do myfunction(1,2) which in reality calls the doit method of the same instance of Singleton everytime. As a more concrete example, you can create a counter function like this:

counter = function(){
    var i = 0;
    return function(){
        return i++;

Each time you call counter() the result increases by 1.

A variation of this pattern is to extend an existing function/method by replacement. This is similar to the ruby practice of aliasing a method to a different name and then sticking a new method in it's place that at some point calls the original version. Anyway, for example, let's say you have an existing function from an existing library... say scriptaculous effects' Effect.Shake. You want to change the default options without having to rename the function(so that all your existing code that depends on it doesn't not need to change), you would do:

    Effect.Shake = function(){
        var original = Effect.Shake;
        return function(element, options){
            original(element, Object.extend({
                distance: 5,
                duration: 0.5
              }, options || {}));

So I've changed the default distance to 5 and duration to 0.5 throughout my app for any calls to shake() by adding this in one place only.

blog comments powered by Disqus