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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.