views:

59

answers:

3

At a website, I found the following code to make a jQuery plugin:

(function($){
  // Our code here...
})(jQuery);

I don't understand how the code above works. What I understand is that the code executes immediately because the very last () in function(){}(). So the entire code says that is an anonymous function that is run immediately.

But I don't understand why the wrapping needs to pass jQuery and that inside it needs $ to be passed.

From my understanding, $ is an alias to jQuery, meaning practically the same. What is the meaning of $ and jQuery here? How does the overall code work as a jQuery plugin?

A: 

You pass the alias $ in function so that it will always refter to JQuery actually. If there are some other libraries included in a certain page such as prototype which also uses $, your code won't break and will work fine.

Sarfraz
+2  A: 

jQuery is the actual parameter. $ is the formal parameter. You could very well write:

(function(ForAFewDollarsLess){
    ForAFewDollarsLess('#myId') ...
})(jQuery);

One reason is convenience - it's short. You might be using jQuery in noConflict mode with other libraries. Maybe typing jQuery all the time is a hassle, or other plugins are following bad practices and using $ instead of jQuery. Either ways, you can use a self-calling function like the one above to solve the problem.

Anurag
A: 

In order to be maximally compatible with other libraries as well, jQuery offers .noConflict(). This removes the $ alias from the global namespace so another library could use it if you want.

If you don't want your plugin to work with .noConflict() it's not necessary.

Using the closure also allows you to not pollute the "global scope" with var's

gnarf