暂时性死区

ES6明确规定,如果区块中存在`let`和`const`命令,这个区块对这些命令声明的变量,从一开始就形成了封闭作用域。凡是在声明之前就使用这些变量,就会报错。

总之,在代码块内,使用`let`命令声明变量之前,该变量都是不可用的。这在语法上,称为“`暂时性死区`”(temporal dead zone,简称TDZ)。

if (true) {
// TDZ开始
tmp = 'abc'; // ReferenceError
console.log(tmp); // ReferenceError

let tmp; // TDZ结束
console.log(tmp); // undefined

tmp = 123;
console.log(tmp); // 123

typeof x; // ReferenceError
let x;

typeof undeclared_variable // "undefined"
}


上面代码中,在let命令声明变量tmp,x之前,都属于变量tmp,x的“死区”。只要用到该变量就会报错.

undeclared_variable是一个不存在的变量名,结果返回“undefined”。

function bar(x = y, y = 2) {
return [x, y];
}

bar(); // 报错


上面代码中,调用bar函数之所以报错(某些实现可能不报错),是因为参数x默认值等于另一个参数y,而此时y还没有声明,属于”死区“。如果y的默认值是x,就不会报错,因为此时x已经声明了。 

function bar(x = 2, y = x) {
return [x, y];
}
bar(); // [2, 2]


以上摘自 http://caibaojian.com/es6/let.html

好记性不如写博客
原文地址:https://www.cnblogs.com/GGbondLearn/p/12057752.html