1. Variable promotion
Before ES6, we needed to use the var keyword to declare a variable, and the variable declared with var had the feature of variable promotion.
In the above code, there is a global scope and a function scope, and variable A is declared in both scopes. When the fn function executes console.log(a), it will first find variable A in its scope.
If it doesn’t, it looks in the global scope.
In the fn function scope we can see the a variable declaration and assignment, but it is below the console.log(a) statement. Normal logic would not find the outer definition of a? But the result was just the opposite.
Code execution flow:
We can divide code into global code and function (local) code by location. Before executing the global code, add window as the global execution context, and then preprocess the global data:
(1) Find the key declaration of var variable, assign the value of undefined, and add the attribute of window. => The variable is promoted
(2) Add fun() to function and add it to window. => The function is promoted
(3) This => assigns window
After the preprocessing ends, the global code is executed.
The function code execution process is similar to the above, but the execution context is involved here, which will be added later.
So we can think of this line of code this way
The end result, of course, is undefined. This is the variable promotion that exists in JS.
2. Function promotion
The principle of function promotion is the same as that of variable promotion. The difference is that function promotion already creates function objects, while variable promotion assigns undefined, which can be understood as variable declaration promotion.
3. Develop
Var fn = function(){} var fn = function(){} var fn = function(){}
If the function is called before, the function object is not created, the variable fn2 is assigned to undefined, so the browser does not recognize it and calls it as a function, so the error is reported.
(2) In JS, functions are the first citizens
Instead of covering fn, we’re covering var fn =3;
Results: