What Is Hoisted Declaration
Variable Hoisted
猜猜看以下的程式,答案是什麼?
1 2 3 4 5 6 7 |
|
事實上他等同以下程式,JavaScript 底層把宣告的動作自動往上提(hoisted)了。
1 2 3 4 5 6 7 8 |
|
Function Hoisted
兩種函式定義
要說明 Function Hoisted 之前,我們拿兩種定義方式來比較: function definition 和 function declaration。
1 2 3 |
|
以及
1 2 3 |
|
兩種函式的 Hoist 比較
以下結果是 TypeError: undefined is not a function
。確實 var b 往上提了,可是函式主體沒有,所以呼叫了 undefined 當函式。
1 2 3 4 5 6 7 8 9 10 11 12 |
|
如果是使用 function declaration,則結果可以正常執行,執行的 b() 會是 w2。因為除了內部的 function b 宣告以外,連函式主體,都往上提了。
1 2 3 4 5 6 7 8 9 10 11 12 |
|