JavaScript中的(function(){})()构造是什么? [英] What is the (function() { } )() construct in JavaScript?

查看:100
本文介绍了JavaScript中的(function(){})()构造是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经知道这意味着什么,但我现在正在努力...

I used to know what this meant, but I'm struggling now...

这基本上是说 document.onload

(function () {

})();


推荐答案

这是立即调用函数表达式,或 IIFE 。它在创建后立即执行。

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

它与任何事件的任何事件处理程序无关(例如 document.onload )。

考虑第一对括号内的部分: function(){} )(); ....它是一个常规函数表达式。然后查看最后一对(function(){})(); ,这通常会添加到表达式中以调用函数;在这种情况下,我们的先前表达式。

It has nothing to do with any event-handler for any events (such as document.onload).
Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

这种模式通常用于避免污染全局命名空间,因为IIFE中使用的所有变量(如同任何其他普通函数)在其范围之外是不可见的。

这就是为什么你可能把这个结构与 window.onload <的事件处理程序混淆了/ code>,因为它经常被用作:

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
    // all your code here
    var foo = function() {};
    window.onload = foo;
    // ...
})();
// foo is unreachable here (it’s undefined)

修正建议< a href =https://stackoverflow.com/users/69083/guffa> Guffa :

Correction suggested by Guffa:


该函数在创建后立即执行,而不是在解析后执行。在执行任何代码之前解析整个脚本块。此外,解析代码并不会自动意味着它已被执行,如果例如IIFE在函数内部,则在调用函数之前它不会被执行。

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.

这篇关于JavaScript中的(function(){})()构造是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆