gpt4 book ai didi

javascript - JavaScript 中的 (function() { } )() 结构是什么?

转载 作者:行者123 更新时间:2023-11-28 08:00:15 25 4
gpt4 key购买 nike

我想知道这意味着什么:

(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/25525724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com