iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0
自我挑戰組

登堂入室!前端工程師的觀念技術 _30_ 題系列 第 4

3. 解釋 Hoisting

在我們之前提到的Execution Context,都會執行一個被稱為"Hoisting的步驟"。

https://ithelp.ithome.com.tw/upload/images/20210904/20129476fUM5tkzyKg.png

https://ithelp.ithome.com.tw/upload/images/20210904/20129476K2YPaIAqse.png

而今天就要來複習hoisting ~

定義


  • initialize var & function

JavaScript Hoisting refers to the process whereby the interpreter allocates memory for variable and function declarations prior to execution of the code.

Declarations that are made using var are initialized with a default value of undefined. Declarations made using let and const are not initialized as part of hoisting.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

而Hoisting執行的行為是: 電腦會先分配記憶體給var和function Declaration。

[var] vs. [let & const]


所以我們要來了解這個行為的影響,
首先,看看let,const和var的例子:

console.log(x); // ReferenceError: x is not defined

let x = 100;  
console.log(x); // ReferenceError: x is not defined

const x = 100;  

如果是用let或const宣告的變數,不會被提前分配記憶體,
就不會提升initialize這個行為,

因此,如果在宣告變數前就使用變數,那麼就會彈出ReferenceError,告訴你變數還未被定義。

console.log(x); // output: undefined

var x = 100;  

然而被用var宣告的變數,這裡的console會告訴你undefined

也就是說,對瀏覽器而言,這個變數已經被初始化過了。
(瀏覽器知道這個變數存在,只是尚未被賦值。)

[Function Declaration] vs. [Function Expression]


使用 Function Declaration 也會被hoisting:

functionDeclaration();  // output: 100

function functionDeclaration(){
    console.log(100);
}

要注意的是,執行Function Expression就不會被進行hoisting:

functionExpression();  // ReferenceError: functionExpression is not defined

const functionExpression = () => {
    console.log(100);
}

而上面是最粗淺的解釋,如果想要深入理解很推薦這篇文章:
我知道你懂 hoisting,可是你了解到多深?

【如果內文有誤還請不吝指教>< 也謝謝閱覽至此的各位:D】

-----正文結束-----

今天比較忙所以打的比較簡單,但之前有看過整理的很好的文章,就也放進來了。


上一篇
2. 解釋 Closure ( Scope chain )
下一篇
4. 關於 Constructor Function
系列文
登堂入室!前端工程師的觀念技術 _30_ 題31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言