The closure wrapper (function($){..})(jQuery);
is a great way to have local variables instead of global ones. Both $
and any variable and local function defined within the wrapper is visible only within the wrapper, not outside. This is great, and I use it all the time.
(function($){
[..]
})(jQuery);
However, I have been wondering why we pass jQuery
(and possibly other stuff) as an argument, instead of using a local variable declaration.
(function(){
var $ = jQuery;
[..]
})();
Wouldn't this work just as fine, and be more transparent?
I see one reason when former way is better:
(function(){
var $ = jQuery;
[..]
var jQuery = foo;
})();
In this example variable "$" will be undefined because of hoisting.
There's an advantage in terms of code length. It saves a few characters (bytes...). It's not much, but if you have to choose between the 2, the first example is shorter.
In the sake of minification, it's also possible (and to some degree common) to use an "unset" variable to serve as an undefined match like this:
(function(r,u){if(r.missingProp===u)alert('undefined!')})({realProp:1})
Since u
isn't passed a value during the call, it will equal undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With