2017-08-27 45 views
1

我有以下文件https://www.codementor.io/cchilder/draft/bcgnrvw5p,我试图解释这一点:为什么在重新分配错误之前在新块中使用let变量?

// 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 /节点解释阅读导致此错误的代码?谢谢

+0

这SO【答案】(https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-not-hoisted-in-es6)解释了这种行为。 –

+0

tl; dr:在赋值之前,您无法访问使用'let'定义的变量。块中的'y'隐藏外部''y',即'console.log中的'y'('新块范围 - x,y,z:$ {x},$ {y},$ {z} ');'指的是内部的'y',它没有一个值,因此抛出一个错误。 –

回答

1

没关系使用旧xy在一个新的块,只要新的块属于老的范围,但既然你已经创造了另一个ylet新的块,根据ES6,新的y将用'未分配'值覆盖旧的y,一旦它被访问而没有分配,就会出现错误。

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