tags:

views:

65

answers:

3

Hi,

I am a bit new to reusable plugins for jquery. I have ran across this code several times and can't figure out exactly what is going on.

(function( $ ){
   ...
})( jQuery );

Can any one enlighten me?

+1  A: 

function( $ ){ /* … */ } is an anonymous function that is directly called with jQuery as parameter. So $ inside the anonymous function is the same as jQuery.

Gumbo
+3  A: 

It allows the author to use the $ function within the plugin without exposing it to the global scope - just keeps things a bit cleaner outside of the plugin itself.

I believe this is best practice for developing jQuery plugins - sure I saw it mentioned in the docs somewhere!

Stephen Orr
By extension, it also allows you to use other libraries in addition to jQuery, such as Scriptaculous or Prototype
dclowd9901
+2  A: 

It creates an anonymous function and executes it immediately, passing it jQuery as a parameter. Since the anonymous function accepts a parameter $, within the function $ is the jQuery object, allowing you to use $ for jQuery objects as you're used to even if $ is being used by something else (such as another library) outside the function. Wrapping code in an anonymous function like this protects against variable naming collisions, because any variable defined inside the function is limited to that function's scope.

Jimmy Cuadra