2017-08-24 93 views
0

有人可以解釋爲什麼這不起作用?檢查typeOf undefined無法正常工作?

setOrientation: function() { 
    if (typeof oldOrientation !== 'undefined') console.log(oldOrientation); 
    let oldOrientation = orientation; 
    //other code 
} 

This throwbacks oldOrientation is undefined。我最終只是刪除了let,它開始工作,但我很難完全理解爲什麼。我認爲這與範圍界定有關?

我已經通過在全球聲明oldOrientation解決了這個問題,我只是想明白爲什麼typeof的比較沒有按照原來的方式工作。

+0

因爲你在函數內部定義它,使之成爲全局函數。 – epascarello

+0

但不管怎麼樣,它不應該比較已經返回'「undefined」,因此不會出現錯誤? –

+3

吊裝....... – epascarello

回答

3

From MDN let:

In ECMAScript 2015, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

意味着你使用的變量之前,它是定義。


如果你習慣使用var,會發生什麼情況是var聲明移到因爲吊裝塊範圍的頂部。所以,下面的函數

function foo() { 
    console.log(typeof bar) 
    var bar = "123"; 
} 

被視爲

function foo() { 
    var bar; 
    console.log(typeof bar) 
    bar = "123"; 
} 

但是當你使用let,他們是沒有提升,因此聲明不被移至塊的頂部。

+0

有一點幫助,但這是否意味着Chrome正在錯誤地處理錯誤? –

+0

我在chrome中運行它並得到''message「:」未捕獲的ReferenceError:oldOrientation沒有被定義「,所以看起來好像它正確地返回了錯誤消息。 – epascarello

+0

@epascarello javascript noob here,我來自c#,很難理解你在說什麼。所以基本上問題是'let'沒有使用變量提升,因此如果用'let'聲明變量,那麼if語句就沒有意義了?但用'var'就可以了? – jdmdevdotnet

2

想象一下這樣的簡單情況:

let a = 1; 

{ 
alert(a); 
let a = 2; 
} 

然後警報(一)會做一個變量查找。這從當前範圍(塊)開始,它有自己的變量聲明()但尚未設置(a = 2),因此其尚未定義。上等於:

let a = 1; 

{ 
let a /* = undefined */; 
alert(a); 
a = 2; 
} 

(即變量的聲明被執行的代碼被稱爲hoisting前...)

+2

這是一個很好的答案,你應該提及吊裝,可能指向一個資源,以瞭解更多關於提升在JS –

+0

對不起,但您是否說因爲提升,在比較時,變量*被聲明,但是當它試圖記錄它時,它是未定義的? –

+0

@rather notsay是的。當一個變量被聲明時,它的設置爲undefined。 –