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();
|
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"); }
|
範例 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();
|
在以上範例中,不論是陳述式放前還是表達式放前,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();
|
以上的範例中,兩次執行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是不是就很清楚了呢~