Skip to content

Instantly share code, notes, and snippets.

@ywwwtseng
Created January 24, 2019 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ywwwtseng/5bbc70cd7d756e4b50faf9c188e74188 to your computer and use it in GitHub Desktop.
Save ywwwtseng/5bbc70cd7d756e4b50faf9c188e74188 to your computer and use it in GitHub Desktop.
Hoisting

Hoisting

為了提高 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 函式。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment