Reputation: 6187
(function ($) {
...
} ) (jQuery);
Upvotes: 6
Views: 145
Reputation: 21
Also called a anonymous callback function, as its unbound to any object, so is strictly 'functional'. A good design pattern when designing plugins with jQuery to avoid conflicts as others pointed out!
Upvotes: 0
Reputation: 51685
In addition to the reason detailed in the other answers, it is (slightly!) faster to access function arguments than global variables.
As long as jQuery.noConflict()
has not been called, this could be written as function($){ … }($)
with the same effect.
Upvotes: 0
Reputation: 92772
This way, you can use $
inside your function scope, but on the outside, jQuery is not clobbering other libraries' use of $
(e.g. Prototype also uses $
, and some people like to mix the two together)
Upvotes: 1
Reputation: 382736
To avoid conflicts with other javascript libraries that also use $
.
This method, however, allows you to use $
in that function at your will, no need to use jQuery
there.
That pattern is also important when writing jquery plugins.
Upvotes: 6
Reputation: 106342
It creates a function, with $
as an argument, and immediately runs that function with jQuery
as the argument. Effectively this will ensure that $
points to jQuery
inside your code, even if jQuery.noConflict()
is used.
Upvotes: 2