模块模式 - 为什么JQuery作为参数传入?

时间:2012-04-24 11:01:49

标签: javascript jquery

我想我理解模块模式,但是为什么有些例子将JQuery作为参数传递出来:

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

如果我没有传入JQuery,我仍然可以通过在模块内部进行$()调用来使用Jquery库。那么为什么有些人这样做呢?

4 个答案:

答案 0 :(得分:16)

这里的想法是你将jQuery作为$传递给inside函数,确保$是jQuery。这通常用于保护使用$的代码,尤其是在使用jQuery以及其他使用$类似mootools的库时。


示例,如果您在<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>

答案 1 :(得分:1)

为了'$'安全'使用。大多数开发人员对'$'而不是jQuery感到更舒服。

当使用$作为全局时,它可能与其他JS库冲突。

答案 2 :(得分:1)

这样你可以使用$作为jQuery的快捷方式。如果不像这样封装它,有时会与其他库发生冲突。

答案 3 :(得分:0)

这是为了确保你的命名空间/范围使用$作为jQuery,而不是像Prototype这样使用$的其他JS库。