This question already has answers here:
Are variables declared with let or const not hoisted in ES6?
                                
                                    (4个答案)
                                
                        
                                2年前关闭。
            
                    
我有以下文档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解释器如何准确读取导致此错误的代码?

最佳答案

只要新块属于旧范围,就可以在新块中使用旧的xy,但是由于您已经使用y在新块中创建了另一个let,根据ES6中,新的y将用'unssigned'值覆盖旧的y,一旦在未分配的情况下访问它,就会出现错误。

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

关于javascript - 为什么在重新分配错误之前在新块中使用let变量? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45901489/

10-13 00:55