Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Javascript Singleton is written like this?

Everywhere I saw an implementation of singleton in javascript in a such manner:

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

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

Here we can see that it returns a function which we must call in order to get an object. Question: Why we can't just write like this:

var Singleton = (function () {

    function privateMethod() {
        ...
    }

    return {
        publicMethod1: function() { },
        publicMethod2: function() { },
    };
})();

Somebody will say that reason is for inheritance support. However, I don't see a difference. Anyway Singleton is an object now.

like image 260
Nursultan Zarlyk Avatar asked Oct 30 '22 03:10

Nursultan Zarlyk


1 Answers

Interesting question, and I'll try a guess.

I see a few reasons:

  • first is pointed by @Steffomio in the comments.
    First version will be instanciated only at the first usage, while second will be instanciated immediately, which could lead to CPU pressure on page load (often an unwanted effect)

  • second is here:

     if (!instance) {
            instance = createInstance();
        }
        return instance;
    

part of the code.

With your version of the code (simple closure evaluation), it could fail if the singleton's script is embedded several times in the webpage.
The first time the singletong will be created, then some line of code modifies it, then another recreates the singleton, and prior modifications are lost.

  • third reason is that many languages can't express auto evaluated functions as easily as in JavaScript. If you look at how to implement a singleton in C#, you'll find a similar pattern, which is probably often translated as is in JavaScript.

  • final reason is inheritance support, as you stated yourself.

like image 182
Regis Portalez Avatar answered Nov 14 '22 23:11

Regis Portalez