views:

94

answers:

5
    (function ($) {
       ...
    } ) (jQuery);
+2  A: 

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.

gnarf
+5  A: 

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.

Sarfraz
Thank you very much! All answers and comment enlightened me!
kaneda
@laramaki: You are welcome :)
Sarfraz
+1  A: 

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)

Piskvor
A: 

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.

Sidnicious
A: 

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!

incidah