JS executes function IIFE immediately

In the most basic function call, we evaluate the identifier of the function as an lvalue (as shown in the figure below). But the expression used to be called by parentheses does not have to be just a simple identifier, it can be any expression that evaluates to a function. For example, the simplest way to specify an expression that evaluates to a function is to use a function expression. As shown in the right image below, we first create a function and then immediately call this newly created function. This kind of function is called an immediately invoked function expression (IIFE) , or simply an immediate function .

There are many names for this kind of function, just understand its meaning, learn its spirit, and use its shape.
Insert image description here
The above figure can also be seen as
const myFunctionName = function(){}

myFunctionName(3)  

is equivalent to

(function(){
    
    })(3)

In fact, it replaces the identifier of the function call with a function expression.

The expression is enclosed in parentheses because the JavaScript parser must be able to easily distinguish the difference between a function declaration and a function expression. If the parentheses are removed, the parser will think that this is a function declaration, not an expression, because the function declaration must have a name, but there is not one here, so an error will be reported after parsing the function keyword; in order to avoid errors, add the small Parentheses indicate to the JavaScript parser that this is a function expression, not a function declaration.

Other ways to call a function immediately:

(function(){
    
    }()); // 不常用,写法比较奇怪,难理解
+function(){
    
    }();
-function(){
    
    }();
!function(){
    
    }();
~function(){
    
    }();

Instead of using parentheses to distinguish function expressions from function declarations, here we use the unary operators +、-、!and ~. This approach is also used to indicate to the JavaScript engine that it is processing expressions, not statements.

Function:
Executing functions immediately can create an independent scope to prevent variable pollution; it is often used when encapsulating libraries, such as jQuery.

Guess you like

Origin blog.csdn.net/ThisEqualThis/article/details/128837337
Recommended