Home>Article>Web Front-end> Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

coldplay.xixi
coldplay.xixi forward
2021-03-22 10:25:04 2549browse

Call function immediately

Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

##Directory

    一, Understand the expression of immediately calling function
  • 2. Does the expression of immediate calling function report an error?
  • 3. The correct posture for using the immediate call function
  • 4. Common usage scenarios
  • Write at the end

(Free learning recommendation:javascript video tutorial)

1. Understand the immediate call function expression

1.1 Mind Map

Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

1.2 What is Immediate Call?
Before we learn more about this, let’s talk about the term “self-execution”. The term for this function in this article may not be completely correct. Everyone has a different understanding of it. We are here Here

is used to call immediately~

to call immediately:

    As the name suggests, the expression is executed
  • as soon as it iscreated.
  • is a
  • JavaScript functionthat will be executed immediately when it is defined.
(function (x) { console.log('x + x = ', x + x);})(5) // x + x = 10
This is a design pattern called

Self-executing anonymous function, which mainly consists of two parts:

    The first part is surrounded by a circle An anonymous function in the bracket operator
  1. (). This anonymous function has an independent lexical scope. This not only prevents external access to the variables in this IIFE, but also does not pollute the global scope.
  2. The second part once again uses
  3. ()to create an immediate execution function expression, and the JavaScript engine will directly execute the function here.
1.3 Core Question

When you declare a function, can it be executed immediately by adding parentheses at the end?

var foo = function(){ console.log('余光');}(); // 余光 成功了! // ...是不是意味着后面加个括弧都可以自动执行?function(){ console.log(''余光);}(); // Uncaught SyntaxError: Function statements require a function name// 什么?还需要一个函数名?不是叫 自执行匿名函数吗?// 我加上了函数名function foo(){ console.log('余光');}(); // Uncaught SyntaxError: Unexpected token ')'
Obviously, the second and third items in the example do report errors, and the error content is different, so where does the problem occur?

Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

#2. Is an error reported when calling a function expression immediately?

Sometimes, after we define a function, we call the function immediately. In this case, we cannot add parentheses directly after the function definition, which will cause a syntax error. The reason for the syntax error is that the keyword

functioncan be used as either a statement or an expression, such as the following:

//语句function fn() {};//表达式var fn = function (){};
In order to avoid parsing ambiguities, the JS engine stipulates, If function appears at the beginning of the line, it will always be parsed into a statement. Therefore, after the JS engine sees the function keyword at the beginning of the line, it thinks that this paragraph is a function definition and should not end with

brackets. In its view,bracketsare just grouping operators.

// 下面这个function在语法上是没问题的,但是依然只是一个语句// 加上括号()以后依然会报错,因为分组操作符需要包含表达式 function foo(){ /* code */ }(); // SyntaxError: Unexpected token ) // 但是如果你在括弧()里传入一个表达式,将不会有异常抛出// 但是foo函数依然不会执行function foo(){ /* code */ }( 1 ); // 因为它完全等价于下面这个代码,一个function声明后面,又声明了一个毫无关系的表达式: function foo(){ /* code */ } ( 1 );

Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE)

3. The correct posture of using the immediate function call

To solve the above problem, it is very simple .

We only need to use

bracesto enclose all the code, because in JavaScriptbrackets ()cannot contain statements, so at this point , when the parser parses the function keyword, it will parse the corresponding code into a function expression instead of a function declaration.

3.1 Common usage postures
// 下面2个括弧()都会立即执行(function () { /* code */ } ()); // 推荐使用这个(function () { /* code */ })(); // 但是这个也是可以用的
3.2 Uncommon usage postures (1)
// 由于括弧()和JS的&&,异或,逗号等操作符是在函数表达式和函数声明上消除歧义的// 所以一旦解析器知道其中一个已经是表达式了,其它的也都默认为表达式了var i = function() { console.log('余光')}(); // 余光true && function() { console.log('余光')}(); // 余光0, function() { console.log('余光') }(); // 余光
3.3 Uncommon usage postures (2)
// 如果你不在意返回值,或者不怕难以阅读// 你甚至可以在function前面加一元操作符号//转boolvar res1 = !function () { console.log('余光');}()console.log('res1:', res1); // 余光 true// 转数字var res2 = +function () { console.log('余光');}()console.log('res2:', res2); // 余光 NaN// 按位非var res3 = ~function () { console.log('余光');}()console.log('res3:', res3); // 余光 NaN
3.4 Uncommon usage postures (3)
There is another situation where the new and void keywords are used, but it is not very common.

void function() { console.log('余光');}();new function() { console.log('余光');}();

4. Common usage scenarios

4.1 Isolation scope
The most common function of IIFE is isolation scope, which was native to JS before ES6 There is no concept of block-level scope, so function scope is needed to simulate it.

Example:

var currentTime = (function () { var time = new Date(); var year = time.getFullYear() var month = time.getMonth()+1; var date = time.getDate(); var hour = time.getHours(); var min = time.getMinutes(); return year + '-' + month + '-' + date + ' ' + hour + ':' + min;})()
You can still declare variables with the same name in other places~

4.2 Lazy function
DOM events are being added for compatibility with modern browsers With IE browser, we need to make a judgment on the browser environment:

var addEvent = (function(){ if(window.addEventListener) { return function(type, el, fn) { el.addEventListener(type, fn, false); } } else if(window.attachEvent) { return function(type, el, fn) { el.attachEvent('on' + type, fn); } }})();
4.3 Use closure to save state
Here I will only give an example for my next article—— "Closures in JavaScript" Let's take a look

var elems = document.getElementsByTagName('a');for (var i = 0; i Note
When the function becomes a function expression that is executed immediately, the variables in the expression cannot be accessed from the outside.

(function () { var name = "Barry";})();// 无法从外部访问变量 namename // 抛出错误:"Uncaught ReferenceError: name is not defined"
Assign IIFE to a variable, not to store the IIFE itself, but to store the result returned after the IIFE is executed.

var result = (function () { var name = "Barry"; return name; })(); // IIFE 执行后返回的结果:result; // "Barry"

Related free learning recommendations:javascript(Video)

The above is the detailed content of Deep understanding of JavaScript Immediately Invoked Function Expressions (IIFE). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete