Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
815 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...