Objective
Before on-line read a lot of knowledge about JS, coupled with their previous reading some classic books (including "Javascrtipt Advanced Programming", "You do not know the JS", "JavaScript language essence", etc.), so review and summarize some of the JS classic problems encountered and difficult.
function declarations and function expressions
Before you introduce any of the iife, distinguish between function declarations and function expressions.
There are two ways to define a function: function declaration and function expression.
1 function declarations (functions declaration), i.e., the form:
function FuncName () {
?? function Body ...
}
Function declarations are characterized by:
- Must have a function name, it cannot be anonymous;
- function declaration Promotion
- It cannot be called directly after the function declaration ();
2 function expressions, the most common form of syntax is:
var funcName = function () {
?? function Body ...
}
function expressions are characterized by:
- can be anonymous;
- No declaration elevation, must be assigned before use
- You can run/Invoke a function after the function expression by adding ()
Second, what is Iife
Iife (immediately-invoked function expression), which is called immediately. The process of creating it is:
1 declare an anonymous function;
2 Call this anonymous function immediately
Typical examples are: (function FuncName () {...}) ()
It also has a variant, which is more useful for code compression, i.e.
!function () {...} ()
“!” The existence of the whole sentence can be seen as a unary operation expression, so that "function () {}" is considered a function expression, the result of the execution as "!" The operand
Iii. role of Iife 1 isolation scopes
The main function of Iife is to isolate the scope.
Before ES6, JS had only a function scope and no block-level scope. So in order to be able to isolate scopes, you can only use a function to frame the code, and then use the so-called immediate execution of the function to simulate the local scope.
For specific examples, see:
Example 1
2 Lazy Loading
That
Lazy loading with iife, because the function is executed in a synchronous manner by the execution engine, so when the subsequent code accesses the variable, the computed filter results can be returned directly.
Four Reference
?? 1 JavaScript advanced programming;
?? 2 What is the immediate execution function? What is the role?;
?? 3 What does this JavaScript code mean?;
?? 4 Why should have JS immediately execute function, what is the meaning of existence?;
JS series The 1th chapter Iife