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?