為了提高 Javascript 在瀏覽器上的效能, Javascript 編譯器會進行名為 Hoisting(提升)的行為,當 JS engine對 Javascript 進行編譯時會同時進行變數及函式的宣告,將他們儲存在記憶體中,然後運行被編譯過的代碼。
sayHi();
function sayHi() {
console.log(words); // undefined
var words = 'Hello';
console.log(words); // Hello
}
讓我們來頗析 JS engine 如何運作以上的代碼
Step 1: JS engine 在執行代碼的前個瞬間,會對它進行編譯和宣告 sayHi 函式。
Step 2: 運行以上的代碼,呼叫 sayHi 函式。
Step 3: JS engine 在執行 sayHi 的前個瞬間,會對它進行編譯,宣告 words 變數並賦值 undefined。
Step 4: 運行 sayHi 函式。