7

I think I understand the module pattern, but why do some examples pass JQuery in as a parameter like this:

Namespace.AppName = (function ($) {
     // Code Here
})(jQuery); 

If I don't pass in JQuery I can still use the Jquery library just fine by making $() calls inside the module. So why do some people do this?

reach4thelasers
  • 26,181
  • 22
  • 92
  • 123
  • possible duplicate of [jQuery dollar sign ($) as function argument?](http://stackoverflow.com/questions/4983150/jquery-dollar-sign-as-function-argument) – Felix Kling Apr 24 '12 at 11:03

4 Answers4

16

The idea here is that you pass jQuery as $ to the inside function, making sure that the $ IS jQuery. This is commonly used to protect code that uses $ especially when using jQuery along with other libraries that use $ like mootools.


example, if you had this code in the <head>

<!--load jQuery-->
<script src="jquery.js"></script>

<script>
    //"$" is jQuery
    //"jQuery" is jQuery 
</script>

<!--load another library-->
<script src="anotherlibrary.js"></script>

<script>
    //"$" is the other library
    //"jQuery" is jQuery 

    //out here, jQuery code that uses "$" breaks

    (function($){
        //"$" is jQuery
        //"jQuery" is jQuery (from the outside scope)

        //in here, jquery code that uses "$" is safe

    }(jQuery));

</script>
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

In order to use the $ 'safely'. Most developers are more comfortable with the '$' instead of jQuery.

When using the $ as a global, it may conflict with other JS libraries.

S P
  • 4,615
  • 2
  • 18
  • 31
1

This is so you can use $ as s shortcut for jQuery. This can sometimes collide with other libraries if you don't encapsulate it like this.

primavera133
  • 1,284
  • 1
  • 15
  • 24
0

This if for making sure that your namespace/scope uses $ as jQuery and not other JS libraries like Prototype, which uses $, too.

binarious
  • 4,568
  • 26
  • 35