javascript - 为什么 jQuery 将自己包装在一个函数中?

标签 javascript jquery

我正在阅读 jQuery source我想知道为什么整个源文件都包含在一个匿名函数中。

(function(){
  ...
})();

这是否有助于避免污染全局命名空间?它为什么存在以及它是如何工作的?

最佳答案

它使用函数体来提供自己的作用域,而不是引入大量可能被外部代码意外更改的全局变量。

例如。

(function (){
    var someConstantValue = ...;
    myCoolFunction = function(){ return someConstantValue * 5; }
})();

myCoolFunction();

如果未引入函数范围,则可能会通过引入其他代码(或其他库)意外更改 someConstantValue

someConstantValue = someOtherValue; // this won't change the behaviour of myCoolFunction

关于javascript - 为什么 jQuery 将自己包装在一个函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/387944/

相关文章:

php - 检查日期并显示直到事件日期

javascript - jQuery 展开/折叠表格行在展开时不显示

jquery - 上传前检查文件扩展名

c# - 使用 jquery 调用链接按钮点击

javascript - FullCalendar Jquery,选择当天内

javascript - 加载和访问二维数组时出现问题

JavaScript:goto 语句

javascript - ApplicationController :Class in rails 4. 2 的未定义局部变量或方法 `gon'

javascript - 无法使用 JQuery 同时添加两个超链接

javascript - ajax 中的服务器响应进入错误函数而不是成功