(function ($) {
...
} ) (jQuery);
views:
94answers:
5It 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.
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.
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)
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.
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!