Friday 24 June 2011

Singletonize revisited

For some reason, yesterday night while musing about how the [[prototype]] (accessible via __proto__ in Firefox and Chrome) and prototype work (I think I've finally fully understood it after all theses years in which I was missing some details) it came to my mind a post that I published 1 year ago.
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