Learning from the jQuery source
Thursday, July 22nd 2010
A while back, I watched a video by Paul Irish titled “10 Things I Learned from the jQuery Source”.
One thing I particularly liked, is the way jQuery has undefined passed as a parameter to its main function.
In JavaScript all variables are declared globally. This makes it really easy for different scripts on the page to “clobber” (to use a Crockford phrase) each other, for example:
// script1.js var name = "Pete";
// script2.js var name = "Sarah";
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Example</title> </head> <body> <script src="script1.js"></script> <script src="script2.js"></script> <script> alert(name); // "Sarah" </script> </body> </html>
Taking this idea a bit further suppose in script1 we changed the value of a built in…
undefined = "Jam";
This is particularly scary as I see lots of code that checks against undefined:
var something; if (something === undefined) { alert(name); // err... no alert shown }
jQuery’s way to get around this is to take an extra parameter to its main function that is never set. Essentially getting its own “copy” of undefined to test against:
(function(window, undefined) { if (foo === undefined) { // works as expected } }(this))
Clever stuff.