(function ($, undefined) {
. . .
})(jQuery);
I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined
as a parameter?
(function ($, undefined) {
. . .
})(jQuery);
I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined
as a parameter?
3 Answers
Reset to default 16Passing $
to the anonymous function ensures that the namespace is protected (i.e. does not conflict with other libraries that also use the $
shortcut).
Oftentimes, undefined
is passed to a function to ensure that the variable is truly undefined
. For example, consider the following code exerpt:
undefined = '123';
if(myVar == undefined)
{
// Will only ever execute if myVar == '123'
}
As noted in the comments though, unless you're writing a plugin or some such, using jQuery(function($) { })
is probably a better approach, since it protects the $
shortcut and also provides a DOMReady event, meaning less code is required to achieve the same result.
If you need to check against undefined
, you might also want to consider using $.noop()
.
It's possible that $
or undefined
might have their values changed by subsequent code, eg. if you're mixing multiple JS libraries, or using multiple versions of a library. By capturing your own copy of $
and undefined
, you guard against that.
(function ($, undefined) {
. . .
})(jQuery);
with that you'll be sure that $ is jQuery inside the function(whatever jQuery is in your script). It doesnt prevent you from overwriting jQuery variable though,so use it only if you really need it( or you are creating a plugin and distributing a jquery plugin).
As for undefined,it will force undefined to actually be undefined,as undefined can be overwritten in some js engines.
$
without fear of some other library overriding it. looking for duplicate. the undefined portion helps with minification if you compare against undefined, otherwise i don't know – Kevin B Commented Apr 1, 2014 at 19:24undefined
is passed. stackoverflow.com/questions/2716069/… – Jonathan M Commented Apr 1, 2014 at 19:26jQuery(function($) { ...
does the same thing with an added DOM ready handler – adeneo Commented Apr 1, 2014 at 19:28