2017-09-29 80 views
0

我對代碼的假設是第二個let x上面的代碼位於時間死區。因此不應該拋出錯誤。瞭解設定範圍

代碼

function f(condition, x) { 
 
    if (condition) { 
 
    let x = 100; 
 
    return x; 
 
    } 
 
    let x = 30; // <---- throw error 
 

 
    return x; 
 
} 
 

 
f(true, 1);

+2

'let'是 「塊作用域」 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/發言/讓 –

+1

我知道讓是塊範圍 – aWebDeveloper

+0

閱讀關於在Javascript中提升,所以你可以瞭解哪些代碼的例子失敗。 – Dez

回答

2

那麼這裏的問題是,你重新聲明同一變量x兩次在同一function,所以變量x將被吊起。

if (condition) { 
    //This x declaration is fine as it wasn't preceded with any others declaration inside the same block scope 
    let x = 100; 
    return x; 
    } 
    //Now this second x declaration will cause the hoisting problem 
    let x = 30; // <---- throw error 

這裏第二let x = 30;聲明衝頂您function範圍x變量。所以得出的結論是,你不能在同一個範圍內多次聲明同一個變量。

有關在Javascript varaible提升進一步的閱讀,您可以檢查:

+1

你可以取出'if(condition)'位,因爲它不是它抱怨的'x'。例如。這很好'{let x = 0; {let x = 0; }}' – Keith

+1

這是錯誤的。 'let' /'const'沒有提升。這個問題是由傳入的參數'x'導致的,它與第二個'let'聲明在相同的範圍內。 'let' /'const'意味着你只能在同一個範圍內綁定一個名字('x')。 – ftor

2

問題似乎是與X已經是具有相同的範圍,因爲外X一個函數參數。如果我更改功能參數xy,代碼工作正常。

代碼

function f(condition, y) { 
 
    if (condition) { 
 
    let x = 100; 
 
    return x; 
 
    } 
 
    let x = 30; // <---- doesnt throw error 
 

 
    return x; 
 
} 
 

 
f(true, 1);