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

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

问题描述

我曾经知道这是什么意思,但我现在很挣扎...

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

这基本上是在说 document.onload 吗?

Is this basically saying 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 的事件处理程序混淆了,因为它经常这样使用:

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)

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.

更新由于这是一个非常受欢迎的话题,值得一提的是,IIFE 也可以用 ES6 的箭头函数(如Gajus 已经指出在评论中) :

Update Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
 // do something with foo here foo
})('foo value')

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

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