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?

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

1 Comment

By extension, it also allows you to use other libraries in addition to jQuery, such as Scriptaculous or Prototype
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.

2 Comments

It creates an anonymous function and executes it immediately. I don't see a function being executed here..
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: markdalgleish.com/2011/03/self-executing-anonymous-functions
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.