The skinny: here’s a neat little trick to reduce the amount of code users have to type to instantiate objects:
function jQuery(str, con){
if ( window == this )
return new jQuery(str, con);
// ...
}
new jQuery("#foo"); // this is now equivalent...
jQuery("#foo"); // ...to this!
{:lang=“js”}
Explanation: when jQuery(“#foo”) is typed, the function first determines if the context in which it’s being called is the global object (window). If it is, it returns an instantiation of itself. When it’s instantiated, the context in which it’s being called is inside its own function, and NOT within the global object (window), thus it bypasses our little instantiation trick and moves on to execute any remaining code in the function.
From John Resig’s Best Practices in Javascript Library Design
Comments