Skip to content

ReferenceError: Cannot access 'x' 之前 initialization

错误信息

                Cannot access 'x' 之前 initialization
              

快速摘要

你 used `let` or `const` 变量之前它 是 declared — JavaScript knows 它 exists (hoisting) 但 won't let 你 access 它 yet.

为什么发生

  • Used let or const 变量之前它的 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?

  • 理解那个 let and const 是 hoisted 但不 initialized 之前它们的行

  • 检查如果 code 是 reordered or moved 到不同函数

如何修复

  • Move declaration above 首先 usage 的变量

  • Restructure code 所以变量是 initialized 之前它 是需要

  • Use var 仅如果你 理解 hoisting differences (不 recommended)

如何预防

  • Declare 变量 at 顶部的 它们的作用域

  • Use const and let consistently and 启用 ESLint 规则

相关资源

相关术语

相关课程

  • 变量

    学习关于变量 hoisting and temporal dead 区域

相关练习

← 返回语言