When executed JS
when the code is generated execution environment .
If the code is written in a function, the function execution environment will be generated , otherwise it will be in the global execution environment . There are only these two execution environments.
Look at the following piece of code:
b(); // call b
console.log(a); // undefined
var a = 'Hello world';
function b() {
console.log('call b');
}
This is because functions and variables are promoted. The usual explanation for promotion is to move the declared code to the top.
But a more accurate explanation is that when generating an execution environment , there will be two stages:
The first stage is the creation stage, the JS
interpreter will find out the variables and functions that need to be promoted, and give them a good space in the memory in advance. If it is a function, store the entire function in memory. Variables are only declared and assigned values undefined
.
In the second stage, the code execution stage, we can use it directly in advance.
In the promotion process, the same function will overwrite the previous function , and the function takes precedence over variable promotion:
b(); // call b second
function b() {
console.log('call b fist');
}
function b() {
console.log('call b second');
}
var b = 'Hello world';
Because it var
will produce many errors, it ES6
is introduced in let
. let
Before a statement can not be used, but this is not often said let
not improve.
let
Improved , the memory has also opened up space for him in the first stage, but because of the characteristics of this statement, it cannot be used before the statement .