Hoisting

JavaScript 在執行時會分為兩個部分,一為創造環境,一為執行。

變數

  • 創造階段
    先被挑出來,並在記憶體上給個空間
  • 執行階段
    賦值
1
2
3
4
5
6
7
// 以下面程式碼為例
var hp = 'Harry Potter';

// 創造
var hp;
// 執行
hp = 'Harry Potter';

函式

  • 創造階段
    函式陳述式:優先載入
    函式表達式:情形同變數
  • 執行階段
    函式陳述式:在創造階段就已能運行
    函式表達式:賦值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 以下面程式碼為例(函式陳述式)
hp1();
function hp1() {
console.log("Harry Potter and the Philosopher's Stone");
}

// 創造
function hp1() {
console.log("Harry Potter and the Philosopher's Stone");
}
// 執行
hp1();

// Harry Potter and the Philosopher's Stone
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 以下面程式碼為例(函式表達式)
hp1();
var hp1 = function() {
console.log("Harry Potter and the Philosopher's Stone");
}

// 創造
var hp1;
// 執行
hp1 = function() {
console.log("Harry Potter and the Philosopher's Stone");
}

// error,顯示 hp1 is not a function

範例 1

1
2
3
4
5
6
7
8
9
function hp() {
console.log('Harry Potter lose the battle.');
}
var hp = function() {
console.log('Harry Potter win the battle.');
}
hp();

// Harry Potter win the battle.

在以上範例中,不論是陳述式放前還是表達式放前,hp()的結果都是Harry Potter win the battle.
以提升的拆解來看,

1
2
3
4
5
6
7
8
9
10
11
// 創造
function hp() {}
console.log('Harry Potter lose the battle.');
}
var hp;

// 執行
hp = function() {
console.log('Harry Potter win the battle.');
}
hp();

在執行階段hp()被賦予了一個新值,覆蓋掉了前面的值,所以此題的答案永遠都是Harry Potter win the battle.

範例 2

1
2
3
4
5
6
7
8
9
10
11
function theBoyWhoLived() {
console.log('Neville Longbottom');
}
theBoyWhoLived();
function theBoyWhoLived() {
console.log('Harry Potter');
}
theBoyWhoLived();

// Harry Potter
// Harry Potter

以上的範例中,兩次執行theBoyWhoLived();得出的結果都是Harry Potter
以提升的拆解來看,

1
2
3
4
5
6
7
8
9
10
// 創造
function theBoyWhoLived() {
console.log('Neville Longbottom');
}
function theBoyWhoLived() {
console.log('Harry Potter');
}
// 執行
theBoyWhoLived();
theBoyWhoLived();

這樣,為什麼兩次執行結果都是Harry Potter是不是就很清楚了呢~

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×