I’ve been developing a plugin for jQuery “jQueryLog” to allow for debugging of chain selectors and return values. If you want to check it out, you can do it here
This is already a second version. The first version was actually an edited jQuery and while doing it I had to read jQuery to understand how the internals worked. The question comes from there:
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
(...)
Is there any big reason for the using a chain of declarations + “comma” instead of just using:
function jQuery ( selector, context ) { ... }
var _jQuery = window.jQuery;
var _$ = window.$;
etc...
The only reason I see here is for the minifier to have less literals that can’t be cut down. But are there any other reasons?
It’s just a shorter way to keep all the variables in the function scope while making sure they aren’t used before they’re defined.
In JavaScript Patterns (Sept. 2010, O’Reilly), Stoyan Stefanov calls it the single
varpattern: