<分区>
我有以下文件 https://www.codementor.io/cchilder/draft/bcgnrvw5p我试图解释这一点的地方:
// declare variables
const x = 1;
let y = 2;
var z = 3;
console.log(`Global scope - x, y, z: ${x}, ${y}, ${z}`);
if (true) {
console.log(`A new block scope - x, y, z: ${x}, ${y}, ${z}`);
// redeclare variables
// const x = 4;
let y = 5;
var z = 6;
}
在 if
block 的顶部,未定义 y
:
$ node variables.js
Global scope - x, y, z: 1, 2, 3
/Users/cchilders/variables.js:9
console.log(`A new block scope - x, y, z: ${x}, ${y}, ${z}`);
^
ReferenceError: y is not defined
我没想到会这样,也不知道该如何解释。我现在:
当我们使用相同的名称重新声明这些变量时,我们删除了对 block 范围内的这些名称的访问:
...
if (true) {
// inside this block, we lost access to the old x and y because they're going to be redeclared inside this block scope...but we can't use them yet, they haven't been declared yet
console.log(`A new block scope - x, y, z: ${x}, ${y}, ${z}`);
// redeclare variables
const x = 4;
let y = 5;
// now we can use the new x and y, 4 and 5 respectively
var z = 6;
}
...
为什么会发生这种情况,JavaScript/Node 解释器究竟是如何读取导致该错误的代码的?