我想知道这是什么意思:
(function () {
})();
这基本上是在说 document.onload
吗?
最佳答案
这是一个 Immediately-Invoked Function Expression , 或 IIFE简而言之。它在创建后立即执行。
它与任何事件的任何事件处理程序无关(例如 document.onload
)。
考虑第一对括号内的部分:(<b>function(){}</b>)();
....它是一个正则函数表达式。然后看最后一对(function(){})<b>()</b>;
,这通常被添加到表达式中以调用函数;在这种情况下,我们之前的表达式。
当试图避免污染全局命名空间时,通常会使用这种模式,因为在 IIFE 内使用的所有变量(就像在任何其他 正常 函数中一样)在其范围之外是不可见的。
这就是为什么,也许,您将此构造与 window.onload
的事件处理程序混淆了。 ,因为它经常这样使用:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
Guffa 建议的更正:
The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.
更新 由于这是一个非常流行的话题,值得一提的是,IIFE 也可以用 ES6's arrow function 编写。 (如 Gajus 已指出 in a comment ):
((foo) => {
// do something with foo here foo
})('foo value')
关于javascript - JavaScript 中的 (function() { } )() 结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228281/