为什么在重新分配错误之前在新块中使用letvariables?

我有以下文件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块的顶部, 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 

我并不期待这一点,也不知道如何解释。 我现在有了:

当我们使用相同的名称重新声明这些variables时,我们删除对块范围内的这些名称的访问:

 ... 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解释器如何读取导致此错误的代码? 谢谢

只要新块属于旧范围,在新块中使用旧的xy是可以的,但是由于您已经在新块中创build了另一个y ,根据ES6,新的y将覆盖老y与一个“未分配”的值,一旦没有分配访问,一个错误出来。

 if(true) { console.log(y); { const x; let y; var z; // your code } }