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

标签 javascript jquery

我想我理解了模块模式,但是为什么有些例子像这样将 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/

相关文章:

javascript - 为什么 React 警告我不要将组件方法绑定(bind)到对象?

javascript - WebSocket 数据压缩

jquery - 尝试使用 jquery 中的 getJson 加载 json 数据

jquery - 管理 jQuery 自定义事件

javascript - ubuntu pm2命令运行node-express站点

javascript - 如何在颜色框中显示 JavaScript 变量

jquery - 在 IE 9 及更早版本中显示页面加载不透明度的加载程序图像不工作

javascript - CKEditor 在焦点/单击时更改配置设置

javascript - 如何选择所有相同的元素并在 jQuery 中获取每个 id

Javascript - ff 和 ie margin-top 问题