0

To avoid global variables in JavaScript code I many times seen that people use this construct:

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

So I have questions: why we need to declare function argument as $ and why we need to pass jQuery object as argument?

Barmar
  • 741,623
  • 53
  • 500
  • 612
WelcomeTo
  • 19,843
  • 53
  • 170
  • 286

2 Answers2

1

You don't have to. You can name the function argument whatever you want it to be. It is just a common/best practice of people using jQuery since it is common to use $ as an alias to jQuery library object.

The reason why you should do it is because there are other libraries that use $ as an alias to their library objects. It is needed to avoid collisions with those libraries since function closure will ensure $ to be jQuery object inside the wrapper function.

Here's an example:

(function (myJqueryAlias) {
     console.log(myJqueryAlias('document') === jQuery('document'));
})(jQuery);
Joon
  • 9,346
  • 8
  • 48
  • 75
  • I know all about $. you should read my updated answer – Joon Sep 02 '13 at 11:55
  • Your `===` test will never pass - jQuery will create a brand new object for `$('document')` every time you invoke it that'll have a different reference each time. – Alnitak Sep 02 '13 at 11:57
  • It does not really matter that $ is already defined by jQuery unless you are 100% sure that $ will never be overwritten by other libraries or by your code. – Joon Sep 02 '13 at 11:57
  • @Juno can I access to jQuery's `$` object within this closure? If I can it's mean that sens of passing jQuery object as parameter is _only avoiding collisions_ when accessing to `$`? – WelcomeTo Sep 02 '13 at 11:59
  • If you want to use $, you just have to name your parameter as $. – Joon Sep 02 '13 at 12:01
0

With this you archive that in this block you still have $ as jQuery and you can still write stuff like "$("selector")" instead of "jQuery("selector")". And outside this block the variable $ is still what it should be (for example you use another JSLib that uses the $ too)

nbar
  • 6,028
  • 2
  • 24
  • 65
  • i.e. within closure I didn't have access to `$` variable? Or the only reason to explicitly pass `jQuery` as `$` is to avoid collisions? – WelcomeTo Sep 02 '13 at 12:04
  • @MyTitle yes when outside of this function jQuery.noConflict() is called then u dont have access to $. See http://api.jquery.com/jQuery.noConflict/ for more informations – nbar Sep 02 '13 at 14:17