最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Module Pattern - why is JQuery passed in as a parameter? - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 16

The 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.

发布评论

评论列表(0)

  1. 暂无评论