The immediately invoked function is the immediately-invoked Function expression (IIFE)

Translation means the function expression that is called immediately

Why is it a functional expression?

First, know the difference between a function declaration and a function expression (a function declaration! = function expression)

// This is called a function declaration
function test1() {
    console.log('test1')}// We assign a function declaration to the form of a variable. This is called a function expression.
let a = function () {
    console.log('hello')}Copy the code

We then call function and variable names by parentheses, called execution symbols, after function names

test1()    //test1
test2()    //hello
Copy the code

Go back here to the term immediately called function expression.

If we add () to the end of the function declaration, we can call it immediately.

function test1() {
    console.log('test1')
}()   // A syntax error was reported

let test2 = function () {
    console.log('hello')
}()   Hello / / output
Copy the code

As you can see from the code above, an execution symbol immediately following a function declaration will give an error, whereas an execution symbol immediately following a function expression will give an error so that we can see. When a function needs to be executed immediately, the function must be expressed

We prefix the function declaration with “+” and “!” , “~”, parentheses, etc., can be used to form function declarations into expressions

+function test1() {
    console.log('test1')} ()!function test2() {
    console.log('test2'(a) ~)}function test3() {
    console.log('test3')
}()

;(function test4() {
    console.log('test4')
})()

let test5 = function () {
    console.log('test5')
}()
Copy the code

The W3C’s recommended specification for immediately executing functions is to enclose function declarations and execution symbols in parentheses

(function() {} ())Copy the code

In practice we usually put the execution symbol outside to make it more legible

(The semicolon is used to avoid code compilation errors. Most of the time we write JS code is not write semicolon, and the JS engine when parsing code will automatically add, but like the following code, parentheses, it can not distinguish which is a group with which, so need to manually add semicolon. Since many developer statements do not end with a mark, it is customary to use a semicolon before immediate functions to avoid this.

; (function() {
    console.log('test4')
})()
Copy the code
  • The characteristics of
  1. You can create a scope that has nothing to do with the outside world (independent scope)
  2. Automatic destruction after completion of execution
  3. Throw a list of properties and methods externally

Source: Bilibili