3

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?

Derek Adair
  • 21,846
  • 31
  • 97
  • 134

3 Answers3

5

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!

Steve Hill
  • 2,331
  • 20
  • 27
  • By extension, it also allows you to use other libraries in addition to jQuery, such as Scriptaculous or Prototype – dclowd9901 Mar 17 '10 at 18:23
5

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
  • 35,686
  • 13
  • 80
  • 98
  • `It creates an anonymous function and executes it immediately`. I don't see a function being executed here.. – doub1ejack Mar 07 '13 at 16:51
  • Ok, it's just syntax that I wasn't fully understanding. The first set of parens contains an anon function and the second set calls that declared function. Here's a good explanation: http://markdalgleish.com/2011/03/self-executing-anonymous-functions/ – doub1ejack Mar 07 '13 at 16:55
1

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844