I came across following implementation of singleton design pattern in javascript.
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;
}
};
})();
APPROACH TWO
var singleton = (function(){
var a = { value: "string"};
return {
getInstance: function(){
return a;
}
};
})();
var ob = singleton.getInstance();
var be = singleton.getInstance();
console.log(ob===be); //logs true
So My question is are there any issue with second approach.
I think there is no need to create a function and let it return an object, instead we can simply create one object and return it through getInstance() method, and since it is IIFE( immediately invoked function), there is only one instance of the object being created, so we any way do not need to have following check if(!instance){instance = createInstance()} rather we should just have immediately invoked function, create an object in that function, which will be private object and then return it through the getInstance method.
MY QUESTION IS : Am i correct in my understanding Or I am missing some point and thus wrong in my implementation of singular in javascript.
Thank you very much