ReferenceError: Cannot access 'x' 之前 initialization
错误信息
Cannot access 'x' 之前 initialization
快速摘要
你 used `let` or `const` 变量之前它 是 declared — JavaScript knows 它 exists (hoisting) 但 won't let 你 access 它 yet.
为什么发生
Used
letorconst变量之前它的 declaration 行Temporal dead 区域 (TDZ) — 变量是 hoisted 但不 initialized
Code 是 reordered 所以 usage 现在 comes 之前 declaration
最小示例
console.log(name);
const name = "Alice";const name = "Alice";
console.log(name);const name 是 hoisted 但 in temporal dead 区域直到它的行 — accessing 它之前 declaration throws ReferenceError.
如何诊断
查找 declaration 行 for 变量 — 是它 之后 usage?
理解那个
letandconst是 hoisted 但不 initialized 之前它们的行检查如果 code 是 reordered or moved 到不同函数
如何修复
Move declaration above 首先 usage 的变量
Restructure code 所以变量是 initialized 之前它 是需要
Use
var仅如果你 理解 hoisting differences (不 recommended)
如何预防
Declare 变量 at 顶部的 它们的作用域
Use
constandletconsistently and 启用 ESLint 规则
相关资源
相关课程
- 变量
学习关于变量 hoisting and temporal dead 区域
相关练习
- Let 对比 Const 测验
测试你的理解的 let/const behavior.
- Predict 变量 Reassignment
Predict 如何变量 behave 之后 reassignment.