Module Pattern - why is jQuery passed as a parameter?

I think I understand the module template, but why do some examples pass jQuery as a parameter like this:

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

If I don’t go into jQuery, I can still use the jQuery library simply by creating $ () calls inside the module. So why do some people do this?

+7
source share
4 answers

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


For example, if you had this code in <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> 
+16
source

To use $ 'safe'. Most developers are more comfortable with "$" instead of jQuery.

When using $ as global, it can conflict with other JS libraries.

+1
source

This means you can use $ as s shortcut for jQuery. Sometimes it may run into other libraries if you don't encapsulate it like this.

+1
source

This is if to ensure that your namespace / scope uses $ as jQuery and not other JS libraries like Prototype, which also uses $.

0
source

All Articles