7

我想我了解模块模式,但为什么有些示例将 JQuery 作为参数传递,如下所示:

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

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

4

4 回答 4

16

这里的想法是你传递jQuery$内部函数,确保$是 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>
于 2012-04-24T11:04:48.657 回答
1

为了“安全”地使用 $。大多数开发人员更喜欢使用 '$' 而不是 jQuery。

将 $ 用作全局时,可能会与其他 JS 库发生冲突。

于 2012-04-24T11:02:59.040 回答
1

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

于 2012-04-24T11:04:24.877 回答
0

这是为了确保您的命名空间/范围使用 $ asjQuery而不是其他 JS 库,如 Prototype,它也使用 $。

于 2012-04-24T11:03:42.577 回答