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?
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?
Share Improve this question asked Apr 24, 2012 at 11:01 reach4thelasersreach4thelasers 26.9k23 gold badges94 silver badges125 bronze badges 1- possible duplicate of jQuery dollar sign ($) as function argument? – Felix Kling Commented Apr 24, 2012 at 11:03
4 Answers
Reset to default 16The idea here is that you pass jQuery
as $
to the inside function, making sure that the $
IS jQuery. This is monly 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>
In order to use the $ 'safely'. Most developers are more fortable with the '$' instead of jQuery.
When using the $ as a global, it may conflict with other JS libraries.
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.
This if for making sure that your namespace/scope uses $ as jQuery
and not other JS libraries like Prototype, which uses $, too.