14

Below is an example of a very popular implementation of the JavaScript Singleton pattern:

var mySingleton = (function() {
    var instance;

    function init() {
        function privateMethod() {
            console.log("I am private");
        }
        var privateVariable = "Im also private";
        var privateRandomNumber = Math.random();
        return {
            publicMethod: function() {
                console.log("The public can see me!");
            },
            publicProperty: "I am also public",
            getRandomNumber: function() {
                return privateRandomNumber;
            }
        };
    };

    return {
        getInstance: function() {
            if (!instance) {
                instance = init();
            }
            return instance;
        }
    };
})();

I have been thinking about it for a while and don't really understand the need of this complexity when we can achieve the same result with this simple code:

singleton = (function() {
    var obj = {
        someMethod: function() {}
    }

    return obj;
}());

Am I overlooking something here?

Badacadabra
  • 8,043
  • 7
  • 28
  • 49
Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
  • possible duplicate of [Difference between Module Pattern and Singleton Pattern?](http://stackoverflow.com/q/13429169/1048572) – Bergi Jul 04 '15 at 17:16

1 Answers1

19

Yes, in most cases you don't need this complexity, and would just do

var singleton = {
    someMethod: function() {}
};

However, the pattern with that getSingleton function does have one advantage: The object is only constructed when the function is called (for the first time), not before the object is actually needed. Depending on the complexity of the object, this can improve memory usage and startup time of your program. It's basically lazy-loading the module.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375