Reasons for temporary dead zone :
ES6
let
It is clearly stipulated that if there are and const
statements ( ) in the block 注意:let、const语句不存在变量提升
, the variables declared by this block for these commands form a closed scope from the beginning . Any use of these variables before declaration will result in an error .
for example:
//场景一:
var a = 10;
function b() {
console.log(a);
let a = 20;
}
b(); // Uncaught ReferenceError: Cannot access 'a' before initialization 初始化前无法访问“a”
console.log(a);
An error will be reported here, because there is let in function b to define a, and the previous console.log(a); will cause a temporary dead zone when used before variable a is declared , so an error is reported.
//场景二:
// TDZ开始
a = 'abc'; // ReferenceError
console.log(a); // ReferenceError
let a; // TDZ结束
console.log(a); // undefined
a = 123;
console.log(a); // 123
An error will be reported here. Before let
the command declares the variable a
, it belongs to the a
"temporary dead zone" of the variable.
//场景三:
let a = a // ReferenceError
The error reported by the above code is also due to the temporary dead zone. When using let
the declared variable, as long as the variable is used before the declaration is completed, an error will be reported. The above line belongs to this situation. a
Before the declaration statement of the variable is executed, a
the value is fetched, resulting in an error" Cannot access 'a' before initialization
"
Extension: Other phenomena that cause temporary dead zones:
let/const
Before the keyword appeared, typeof
the operator was 100% safe, and now it will also cause a temporary dead zone. Like the way import
keywords introduce public modules, use new
, and class
create classes, it will also cause a temporary dead zone. The reason is the variable The order of declaration and use
Contrary to the above keywords, keywords such as var
, function
and so on will not be TDZ
affected by (temporary dead zone). If they are accessed before the variable is common, the return result is undefined
because they have variable promotion