javascript 有一個特性為 “hoisting”


 

查了 w3schools 可以看到解釋為

Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

簡單來說 hoisting 就是 javascript 會把變數宣告提升至此 scope 的最頂端來執行。

PS. 很重要的一點,僅將宣告提升至頂端,並不包含變數的初始化

我想這樣說還是很不清楚,來看例子吧!


var x='123';

console.log(x+y);

var y='456';    // 試著把這行拿掉看看,會發生錯誤( y is not defined )

你會發現輸出 123undefined,這就是 hoisting 的特性,將變數宣告提升至頂端(但不包含初始化)

同樣的 hoisting 特性,也適用在函式宣告,因此我們可以先使用函式再宣告。

如:


x();

function x()
{
函式要做的事......
}

參考資料:

http://www.w3schools.com/js/js_hoisting.asp

1 Comment

Leave a Reply