【发布时间】:2012-05-05 00:19:04
【问题描述】:
我想我了解模块模式,但是为什么有些示例将 JQuery 作为这样的参数传入:
Namespace.AppName = (function ($) {
// Code Here
})(jQuery);
如果我不传入 JQuery,我仍然可以通过在模块内调用 $() 来很好地使用 Jquery 库。那么为什么有些人会这样做呢?
【问题讨论】:
标签: javascript jquery
我想我了解模块模式,但是为什么有些示例将 JQuery 作为这样的参数传入:
Namespace.AppName = (function ($) {
// Code Here
})(jQuery);
如果我不传入 JQuery,我仍然可以通过在模块内调用 $() 来很好地使用 Jquery 库。那么为什么有些人会这样做呢?
【问题讨论】:
标签: javascript jquery
为了使用 $ '安全'。大多数开发人员更喜欢使用 '$' 而不是 jQuery。
使用$作为全局时,可能会与其他JS库冲突。
【讨论】:
这是为了确保您的命名空间/作用域使用 $ 作为 jQuery 而不是其他 JS 库,如 Prototype,它也使用 $。
【讨论】:
这样你就可以使用 $ 作为 jQuery 的快捷方式。如果你不这样封装,它有时会与其他库发生冲突。
【讨论】:
这里的想法是将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>
【讨论】: