I watched John Resig’s Best Practices in JavaScript Library Design presentation; one slide suggested "tweaking" the object constructor so it instantiates itself.
function jQuery(str, con) {
if (window === this) {
return new jQuery(str, con);
}
// ...
}
With that, new jQuery("#foo") becomes jQuery("#foo").
I thought it was rather interesting, but I haven’t written a constructor like that in my own code.
A little later I read a post here on SO. (Sorry, I don’t remember which or I’d supply a link. I will update the question if I can find it again.) One of the comments said it was bad practice to hide new from the programmer like that, but didn’t go into details.
My question is, it the above generally considered good, bad, or indifferent, and why?
This is a defensive technique for when people forget to use the
newoperator in front of a ‘class’ function.The logic is that if the function is called without
new, then the global scope will still be the current scope (instead of the new instances), and so we just call the same function using thenewoperator.But if you ask me, the correct thing would be to throw an error and actually let the developer know that it has made a mistake instead of just ‘accepting’ it.
But hey, I guess its according to the jQuery mantra:
‘instead of enabling users to write quality code, enable/force them to write illogic and invalid code’.