Here is a common practice in JavaScript:
(function($) {
...code...
})(jQuery);
I understand the wrapper function (it prevents pollution of the global namespace), but many libraries (like jQuery, Underscore, etc.) already define short names ($
and _
, respectively) at global scope for me to use. I wonder what the advantage to this approach is. Just to rename jQuery
to something shorter? Prevent me from overwriting $
? Make it easier to swap in another library later? I guess none of these seem really convincing to me.
Furthermore, I have also seen this:
(function(_) {
...code...
})(_);
Nothing is even renamed here. I have even seen:
(function(global) {
...code...
})(this); // or window, perhaps
What is wrong with just using window
directly?
So here's what I'm asking:
this
or window
as a reference to global scope?Does this practice have a name?
The syntax is referred to as a self-executing anonymous function. I'm not aware of any special name for passing global objects to the function.
What are the advantages to this practice?
var
scoping variables within the function will
help de-clutter the global namepace.The jQuery
example is typically used in plugins so that the plugin can make use of $
while remaining compatible with $.noConflict()
(docs)
(function($) {
...code...
})(jQuery);
In general, passing global or reserved objects (like window
, document
) as parameters can help reduce the size of your script after minification:
(function(window, document) {
// A JS minifier can now minify the all occurrences of `window` and
// `document` within this function.
})(window, document);
Should I always pass in libraries I'm using rather than use them directly?
Should I pass in this or window as a reference to global scope?
Only if minification or conflicting library variable names are a concern.