跳到主要内容

暂时性死区 Temporal Dead Zone

ES6 中的展暂时性死区

let e = 12;
(function() {
console.log(e);
let e = 123;
})();

在ES6中,根据对let/const的解释中,有这样 段话:

当变量的词法环境被实例化时,变量才会被创 建,而且,只有在变量的词法绑定被赋值(若没有赋 初始值,则初始化为undefined)进行完成过后,变 量才可以被访问,而这中间的区域,就叫做晢时性死 Temporal Dead Zone, 简称 TDZ.

tip:const声明的变量,叫做固定变量,并非不可改变,只是不可再赋值而己,这两者是有很大区别的。

let e = 12;
(function0{
// TDZ start
console.log(e); // 报错
let e = 123; // TDZ end,包含此行
console.log(e); // 正常,已不在 TDZ
});
let x = x;
typeof x;
let x = 123;

TDZ 和传参预设值

function test(x = y, y = 1) {
console.log(x, y);
}
test();
test(1);
test(undefined, 1);

函数参数作用域

let x = 1;
function foo(a = 1, b = function() { x = 2 }) {
let x = 3
b()
console.log(x , '1');
}
foo();
console.log(x, '2')