我想我理解了模块模式,但是为什么有些例子像这样将 JQuery 作为参数传入:
Namespace.AppName = (function ($) {
// Code Here
})(jQuery);
如果我不传入 JQuery,我仍然可以通过在模块内调用 $() 来很好地使用 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>
关于javascript - 模块模式 - 为什么 JQuery 作为参数传入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10296615/