← 中文资源

简体中文版本

暂时性死区抛出 ReferenceError

let/const 声明会提升但保持未初始化,声明行执行之前访问就会抛出 ReferenceError,这段窗口就是暂时性死区;var 则被提升初始化为 undefined,读取不会抛错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ReferenceError: Cannot access 'phase' before initialization
after declaration: done
reassign const -> TypeError
var reads undefined

实现说明

真正干活的是函数 probe、probeVar,其余都是接线。

使用要点

  • 演示输出是带标签的(after declaration:、reassign const ->),每个操作都会留下自己的一行标注。

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 probe、probeVar。

入口签名:function probe()

核心语句

return phase; // declared below: still inside the temporal dead zone
} catch (error) {
return `${error.constructor.name}: ${error.message}`;
return `var reads ${legacy}`;

代码示例

// let/const bindings are hoisted but stay uninitialized until the
// declaration line runs — that window is the temporal dead zone, and
// any access in it throws a ReferenceError instead of reading undefined
function probe() {
  try {
    return phase; // declared below: still inside the temporal dead zone
  } catch (error) {
    return `${error.constructor.name}: ${error.message}`;
  }
  let phase = 'run';
}

console.log(probe());

let phase = 'done';
console.log('after declaration:', phase);

// Reassignment of const fails with TypeError — a different error class
const limit = 3;
try {
  limit = 4;
} catch (error) {
  console.log('reassign const ->', error.constructor.name);
}

// var has no dead zone: hoisting initializes the binding to undefined
function probeVar() {
  return `var reads ${legacy}`;
  var legacy = 'hoisted';
}
console.log(probeVar());