问题
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