Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dollar sign ($) as function argument?

I understand JavaScript closures, and I've seen this done in native JS:

(function () {   // all JS code here })(); 

But, what does adding the jQuery spice do?

(function ($) {   // all JS code here })(jQuery); 
like image 659
ma11hew28 Avatar asked Feb 13 '11 08:02

ma11hew28


2 Answers

When you see:

(function() {   // all JS code here })(); 

It is knows as self-invoking anonymous function. The function executes as soon as it is parsed because of the addition of () at the end (that's how you run js functions).

Notice that extra outer braces are just convention, you could also write it up like:

function() {   // all JS code here }(); 

But that convention is heavily used all around and you should stick to it.

(function($) {   // all JS code here })(jQuery); 

Here, $ is mapped to jQuery object so that you could use $ instead of jQuery keyword. You could also put some other character there too:

(function(j) {   // all JS code here })(jQuery); 

Here, j is mapped to jQuery object instead.

Notice also that arguments specified to self-invoking function remain within the scope of that function and do not conflict with outer scope/variables.


I had written an article on the subject, please check it out:

  • Javascript Self-executing Functions
like image 76
Sarfraz Avatar answered Sep 20 '22 01:09

Sarfraz


Its a way of mapping jQuery to the $ in a way so that not all code in a page will see it.

Maybe you have an existing script that uses jQuery that you like to reuse but you also use prototype that also uses $ in the same page.

By wrapping any jQuery using code in that construct you redefine $ to jQuery for the contained part without coming into conflict with other code in the page.

like image 28
David Mårtensson Avatar answered Sep 17 '22 01:09

David Mårtensson