The singleton patterns was documented as a solution to a simple problem, “Only one object of class X can be instantiated at any time in the application”

Typically a singleton is implemented by restricting access to the class constructor, effectively making impossible to instantiate the class

It is common to use singletons for application wide configuration or database access classes.

If you worked with ExtJS framework before you most likely have used a singleton often, the Ext singleton is the framework entry point, and only one instance of that object is ever executed during the live cycle of the application

Singletons are completely supported in JavaScript without any further coding, meaning they are part of the language, although they are not as useful as they could, as there is no support of private variables or members.

1
2
3
4
5
6
7
8
9
10
var singleton = {
    value : 500
};

var ex1 = singleton;
var ex2 = singleton;

ex2.value = 100;

console.log (ex1.value); //output 100
As you can see the lack of support for private members narrows the potential uses.

Fortunately the classical singleton implementation can easily be achieved in JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var singleton = function(options)
    //private methods and variables
    function singletonInstance(options)
        this.options = options || {};
    };
    var myInstance;
    return
        //public methods and variables
        getInstance : function(options)
            if(myInstance == undefined)
                myInstance = new singletonInstance(options);
            }
            return myInstance;
        }
    }
}();

var ex1 = singleton.getInstance({value: 100});
var ex2 = singleton.getInstance();

ex2.options.value = 200;

console.log(ex1.options.value);//outputs 200

As you can see this is a more complex solution but the advantage is that we can have public and private members.

In our situation, as we pretend to extend Ext, or more precisely we are creating code intended to be used by other code, not exposing our internal logic is very useful as we only need to worry about backwards compatibility for our public interface and not for our internal code

This code introduces some key factors:

To create an auto executing function or object the trick is to add () to the end of its declarations, like this:

1
2
3
function foo()
    //some code
}()

Private and public members are also easy to achieve, let’s think a bit how a regular function works, we have some code and then return a value.

What if instead of returning a value we return an object?

Voila!

That’s the secret, everything inside the return object will constitute our public interface, and everything else will be private.

1
2
3
4
5
6
function foo(){
    //this is private
    return {
        //this is public
    }
}

See how easy it is?