IIFE - MDN Web Docs Glossary: Definitions of Web-related terms 编辑
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
(function () {
statements
})();
It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts:
- The first is the anonymous function with lexical scope enclosed within the
Grouping Operator
()
. This prevents accessing variables within the IIFE idiom as well as polluting the global scope. - The second part creates the immediately invoked function expression
()
through which the JavaScript engine will directly interpret the function.
Examples
The function becomes a function expression which is immediately executed. The variable within the expression can not be accessed from outside it.
(function () {
var aName = "Barry";
})();
// Variable aName is not accessible from the outside scope
aName // throws "Uncaught ReferenceError: aName is not defined"
Assigning the IIFE to a variable stores the function's return value, not the function definition itself.
var result = (function () {
var name = "Barry";
return name;
})();
// Immediately creates the output:
result; // "Barry"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论