jQuery dollar sign ($) as function argument?
Asked Answered
C

4

51

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);
Collete answered 13/2, 2011 at 8:11 Comment(1)
in this case $ could be anything it will become jquery object inside this function , $function(y){})(jQuery);Farthest
M
38

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.

Mediocrity answered 13/2, 2011 at 8:21 Comment(1)
Note you can map any argument in this way, not just jQuery to $, valuable in preventing variable hoisting outside the IIFE function scope.Fortnight
I
57

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:

Incommunicado answered 13/2, 2011 at 8:17 Comment(4)
But, isn't $ an alias for jQuery by default?Collete
@MattDiPasquale: That is what I said in my answer, it is made alias with (function($) { // all JS code here })(jQuery); ...............Incommunicado
Firebug Console doesn't give detailed error messages this way. I'm just getting "Lovers is not defined."Collete
(function(){ alert("o"); })() is ok but function(){ alert("o"); }() is not in Chrome/Firefox's Console, so I think it's not a convention that should stick to (as mentioned in your answer), it's a must?Neoplasticism
M
38

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.

Mediocrity answered 13/2, 2011 at 8:21 Comment(1)
Note you can map any argument in this way, not just jQuery to $, valuable in preventing variable hoisting outside the IIFE function scope.Fortnight
H
17
(function() {
   // all JS code here
})();

Is an Immediately-Invoked Function Expression (IIFE), pronounced "iffy". Some people also call them "anonymous, self-executing functions", or just "self-executing functions".

(function(aParameter) {
   alert(aParameter);  // will alert "an argument"
})("an argument");

Here's an IIFE which takes the parameter 'aParameter' and passes itself the argument "an argument".

(function($){
   alert($(window).jquery);  // alert the version of jQuery
})(jQuery);

This one is similar, but "jQuery" (THE jQuery object instance) is the argument to the IIFE, and in this case, jQuery gets passed as the '$' parameter. In this way, simply by typing '$', the body of the IIFE has access to jQuery and its members. This is a common jQuery convention, and it's common for people writing jQuery plugins to maintain this convention in this way.

Not only does the above code maintain the jQuery convention, it also ensures that neither you nor anyone else can accidentally break that convention. E.g., take the following code:

var $ = function() {
   alert('foo');
}

This code turns '$' into something which is definitely not jQuery. If someone did this in some other code outside your plugin code, and then you didn't explicitly pass jQuery as '$' to your plugin, then you wouldn't be able to use '$' as jQuery like you usually do.

Hyperform answered 16/10, 2011 at 3:47 Comment(1)
IIFE is the more common vernacular for self-executing functions.Fortnight
G
12

There are two reasons to pass jQuery into a closure in this way.

By far the most significant one is that it makes your code work on pages which use jQuery's "no conflict" mode, which allows the use of jQuery alongside other libraries which want control over the $ global. For this reason, the (function($) { ... })(jQuery) technique is strongly recommended when writing jQuery plugins.

The secondary reason is that it makes $ a local variable in the scope of the self-executing function and local variable access is (marginally) faster than global variable access. Personally, I don't consider this a very compelling reason — I can't imagine a scenario in which the overhead of using jQuery rather than DOM methods would be acceptable, but that of accessing jQuery as a global variable wouldn't. :-)

I'd say that the best reason to use this technique when not writing a plugin is for consistency — you're less likely to forget to do it when it is important if you're in the habit of doing it when it isn't. Besides, you never know when you'll have the opportunity to recycle code!

Gramophone answered 13/2, 2011 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.