Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - 什么是JavaScript中的(function(){})()构造?(What is the (function() { } )() construct in JavaScript?)

I used to know what this meant, but I'm struggling now...(我曾经知道这意味着什么,但是现在我正在努力...)

Is this basically saying document.onload ?(这基本上是在说document.onload吗?)

(function () {

})();
  ask by Exitos translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's an Immediately-Invoked Function Expression , or IIFE for short.(它是立即调用的函数表达式 ,简称IIFE 。)

It executes immediately after it's created.(它在创建后立即执行。)

It has nothing to do with any event-handler for any events (such as document.onload ).(它与任何事件的任何事件处理程序无关(例如document.onload )。)


Consider the part within the first pair of parentheses: ( (function(){}) )();(考虑第一对括号中的部分: ( (function(){}) )();) ....it is a regular function expression.(....这是一个正则函数表达式。) Then look at the last pair (function(){}) (()) ;(然后看最后一对(function(){}) (()) ;) , this is normally added to an expression to call a function;(,通常将其添加到表达式中以调用函数;) in this case, our prior expression.(在这种情况下,我们的先前表达。)

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.(当试图避免污染全局名称空间时,通常使用此模式,因为IIFE内部使用的所有变量(如在任何其他常规函数中一样)在其范围之外不可见。)


This is why, maybe, you confused this construction with an event-handler for window.onload , because it's often used as this:(这就是为什么您可能将此构造与window.onload的事件处理程序混淆的原因,因为它经常被这样使用:)
(function(){
    // all your code here
    var foo = function() {};
    window.onload = foo;
    // ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa :(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在函数内部,则直到调用该函数后,它才会被执行。)

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 ) :(更新由于这是一个非常受欢迎的话题,值得一提的是,IIFE也可以使用ES6的arrow函数编写(就像Gajus 在评论中指出的那样):)

((foo) => foo)('foo value')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...