我有以下文件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
我没想到这一点,也不知道如何解释。我现在有:
当我们使用相同的名称重新声明这些变量时,我们删除了对块范围内这些名称的访问:
...
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解释器究竟如何读取导致此错误的代码?
答案 0 :(得分:1)
只要新块属于旧范围,就可以在新块中使用旧的x
和y
,但是因为您已经创建了另一个y
根据ES6,使用let
的新版块,新y
将使用“未分配”值覆盖旧y
,一旦访问而未分配,则会出现错误。
if(true) {
console.log(y);
{
const x;
let y;
var z;
// your code
}
}