Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern in JavaScript

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?

like image 312
Gurpreet Singh Avatar asked Jul 04 '15 16:07

Gurpreet Singh


People also ask

What is Singleton pattern in JavaScript?

Singleton design pattern exposes a single instance that can be used by multiple components. Singleton is a design pattern that tells us that we can create only one instance of a class and that instance can be accessed globally. This is one of the basic types of design pattern.

Should I use singleton in JavaScript?

Singletons reduce the need for global variables which is particularly important in JavaScript because it limits namespace pollution and associated risk of name collisions.

What is Singleton design pattern with example?

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.


1 Answers

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.

like image 77
Bergi Avatar answered Oct 10 '22 01:10

Bergi