Singleton pattern in JavaScript

一世执手 提交于 2019-12-03 12:38:40

问题


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:


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.



来源:https://stackoverflow.com/questions/31222765/singleton-pattern-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!