js detailed es6 let TDZ (temporary dead zone)

Reasons for temporary dead zone :

ES6letIt is clearly stipulated that if there are and conststatements ( ) 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 letthe 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 letthe 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. aBefore the declaration statement of the variable is executed, athe value is fetched, resulting in an error" Cannot access 'a' before initialization"

Extension: Other phenomena that cause temporary dead zones:

let/constBefore the keyword appeared, typeofthe operator was 100% safe, and now it will also cause a temporary dead zone. Like the way importkeywords introduce public modules, use new, and classcreate 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, functionand so on will not be TDZaffected by (temporary dead zone). If they are accessed before the variable is common, the return result is undefinedbecause they have variable promotion

Guess you like

Origin blog.csdn.net/qq_44094296/article/details/125390773