Immediately call a function (IIFE)

definition:

IIFE: Immediately called function expression, the function is called immediately when the function is declared.


 

grammar:

The common writing method of IIFE: These two writing methods have the same function, but the expression is different, () only plays the role of self-execution

(function(){...})() parses the function as an expression, and then executes the parsed function [equivalent to var a = function(){}; a(); a gets the function ]

(function(){...}()) is to directly execute the function expression and execution as a statement [equivalent to var a = function(){}(); a gets the result]

Traditional writing:

Declaration: function func(){...}

Call: func();

Other ways of writing IIFE:

!function foo() {...}();

+function foo() {...}();


 

The difference between IIFE and traditional writing:

IIFE: It encloses the function declaration with a () to let the js compiler know that this is a function that needs to be executed immediately;

Traditional: After a function is declared, the function is executed only when it is called, and directly pollutes the global namespace.

Note: The so-called not to pollute the global namespace is because IIFE creates a new function scope, and your real business code is encapsulated in it, so it will naturally not touch the global object. If you need the global object, then pass to the IIFE:

void function (global) {
    // here, global is the global object
}(this) // in browsers, this is the window object


 

Why use IIFEs:

  In js, only function can achieve scope isolation. If you want to isolate the definition of variables, functions, etc. in a piece of code, you can only encapsulate this code into a function.

       In our usual understanding, the purpose of encapsulating code into functions is for reuse. In JS, of course, the purpose of declaring functions is also for reuse in most cases, but due to the lack of scope control methods in JS, we often see functions that are only used once: this is usually the purpose of isolating the scope ! Since it is only used once, execute it immediately! Since it is only used once, the function name is also omitted! This is where IIFE comes in.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653725&siteId=291194637