Possible Duplicate:
Difference between (function(){})(); and function(){}();
google了很多:
(function(){/*code*/})
为什么他们将函数包含在括号内?
两者之间的区别是:
function(){/*code*/}
?
编辑
好的,问题应该是这样的:
为什么他们将他们的代码包含在其中:
(function(){/*code*/})();
而是直接把代码写进js流?
有什么好处,不同的行为吗?
我通常使用立即函数来控制变量范围,以免污染全局命名空间。这是一个非常有用的模式。
(function (window, $, undefined) {
// This pattern gives you the following benefits:
// * all variables defined in here are private
// * can safely minify global variables: window, jQuery & undefined
// * ensures that window, $, undefined mean what you expect
// * global variables are localized so lookups are faster
}(this, jQuery));
所以即使有人使用 window = 'Bob'
或者快捷方式 $
不等于 jQuery
而是 Prototype 库,这个即时函数中的代码仍然可以正常工作。虽然您可能会想“我永远不会将 undefined
设置为其他内容”,但请记住,您不是唯一将代码放入页面的人;您无法承受 DoubleClick 编写糟糕的广告脚本导致网站崩溃的后果,尤其是当它很容易被阻止时。
JavaScript 的全局作用域就像一个公共(public)厕所。你不能总是避免它,但要尽量减少与表面的接触。