We used to think of var a = 2 as a declaration, while the JavaScript engine actually didn't. He treats var a and a = 2 as two separate declarations, the first is the task of the compilation phase, and the second is the task of the execution phase.
--"You don't know the JS"
Variable Promotion
The concept of variable promotion is well known, simply because the compiler promotes the declaration of a variable to the top of its scope (not the global scope) before the code executes. But there are some details that need to be noted in the process. For example, the relationship between assignment and declaration promotion. Let's look at an example first.
Because of the variable declaration promotion, the Declaration of a has been promoted to the front, where the value of the print variable A does not throw an referenceerror (A is not defined) exception. But the strange thing is that the value of a is undefined , which means that the assignment of a variable is not promoted with the promotion of the variable declaration, but is still left in place. Is the same as the appearance.
function Declaration Promotion
As with the elevation of a variable declaration, just declaring a function is no longer a variable. Just like this var a = > function a() {...} . Let's look at an example.
Because of a function declaration promotion, the function foo is executed to print out a value of 2. But there is also a detail to note here.
As you can see here, the function declaration is promoted, but the function expression does not. The reason for this is the same as the above variable assignment. The declaration of the variable foo is first promoted, and the operation of assigning an anonymous function to the variable foo is left in place. Like this.
When executing to foo (), here Foo is just a small variable with a value of undefined and has not been changed to a function. A function call to a undefined of course throws a TypeError error.
In this case, there is also a named function expression (not an anonymous function expression), which is often misunderstood by the person (me). See example.
Why does Referenceerror appear? Start with how the function is declared. Functions have only two ways of declaring them.
- General function declarations: function foo () {}
- function Expression declaration: var foo = function () {}; must be an anonymous function after the equals sign
for var foo = function bar () {}; This named function expression declares a function in the same way as an ordinary function expression. But the bar at this point is just an internal property of Foo (), which is why the above example throws Referenceerror.
Declaration elevation problem in JS