After refreshing my mind reading the article, and in light of my improved JavaScript skills, I have to say that the solution there was overcomplicated, and can be replaced with something utterly more simple:
function singletonize(initialFunc){
if (initialFunc._singletonized)
return initialFunc;
//this is the new constructor that will replace the initial one and that we'll return
var singletonized = function(){
if (initialFunc._singletonInstance)
return initialFunc._singletonInstance;
else{
//just call the initial constructor with the this object that has been passed to the singletonized contructor
initialFunc.apply(this, arguments);
initialFunc._singletonInstance = this;
return initialFunc._singletonInstance;
}
};
//essential to make the prototype thing work
singletonized.prototype = initialFunc.prototype;
initialFunc._singletonized = true;
return singletonized;
}
Find the whole code here
No comments:
Post a Comment