# Explain the differences on the usage of foo between function foo() {} and var foo = function() {} > 前面的是 function declaration (以 function 形式宣告); 後面的是 function expression (以變數形式宣告)。 ## 差異:hoisting 的方式不同 > Hoisting 這個現象,或是說我們可以在程式執行到宣告的那一行之前,就去使用一個變數或函式,是由於JS Engine 在 compile 我們的code時,在 Execution Context 裡分成 Creation Phase 和 Execute Phase 這兩個階段。 JS Engine 在 Creation Phase 時已經空出給函式和變數的記憶體空間。 - 如果是函式(function declaration) 的話,整個function的內容都會被放入記憶體之中。 - 如果是變數(function expression) 的話,因為這個時候變數還沒有被賦值(在 Execution Phase 時才會被賦值),所以會給他一個 undefined 值。 **Function Declaration** ```jsx= foo(); // 'FOOOOO' function foo() { console.log('FOOOOO'); } ``` **Function Expression** ```jsx= foo(); // Uncaught TypeError: foo is not a function var foo = function () { console.log('FOOOOO'); }; ``` ## 總結 - function declaration: hoisting 行為跟 function 一樣,所以呼叫他的位置就算寫在 function 的前面也沒關係。 - function expression: hoisting 行為跟 variable 一樣,所以如果呼叫他的位置寫在 expression 前面的話,會拋出錯誤:`Uncaught TypeError: foo is not a function` ## 延伸閱讀 1. Function Declaration 和 Function Expression 更詳細的說明 [IIFEs 立即函式 - HackMD](https://hackmd.io/WYuvHYzIQWKxPS8MX4kUGQ) 2. hoisting 更詳細的說明 [Hoisting 與 JavaScript 運作原理(1) - HackMD](https://hackmd.io/FnRq72weSwqoyPal7jAh3w)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up