码迷,mamicode.com
首页 > 其他好文 > 详细

IIFE

时间:2019-06-27 00:41:09      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   tps   operator   bar   class   argument   use   ping   ret   

IIFE

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 executing function expression () through which the JavaScript engine will directly interpret the function.

 

ExamplesSection

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 name 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"

 

扩展阅读

JavaScript Design Patterns and IIFE

 

 

 

 

 

IIFE

标签:style   tps   operator   bar   class   argument   use   ping   ret   

原文地址:https://www.cnblogs.com/chucklu/p/11094566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!