(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?
Passing $
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()
.
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