iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
1
Modern Web

從Stack Overflow學前端系列 第 6

從StackOverflow上學CODING(6)宣告一個變數並賦予一個函式值與建立一個函示並命名的差別

var functionName = function() {} vs function functionName() {}
宣告一個變數賦予一個函式與建立一個函示並命名的差別

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.
我最近開始維護別人的js程式碼、維護bug與加入新功能與整理等等
The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.
先前的開法者用了兩種不同的方式來宣告函數但我不太理解用不同方式的意思在哪
The two ways are:
以下為兩個不同的方式

> var functionOne = function() {
>     // Some code
> };
> function functionTwo() {
>     // Some code
> }

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?
請問使用兩種不同的方式的理由為何?其各自的優勢與劣勢是那些?有哪些功能是其中一個方法能達成而另一個不行的呢?


最熱門的兩個回答:
The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).
不同的點在於 functionOne 是一個函式陳述式,它只會在程序一直執行到它的時候才會執行這個陳述式,但是 functionTwo 是一個函式宣告而他在被定義後馬上會抬升到script執行時最優先的順序(hoisting的問題)
For example, a function expression:
舉例來說:一個函式陳述式 且會報錯:

// TypeError: functionOne is not a function
functionOne();

var functionOne = function() {
  console.log("Hello!");
};

And, a function declaration:
一個函式宣告,其函式宣告的順序會被抬升,所以不會報錯且會順利執行

// Outputs: "Hello!"
functionTwo();

function functionTwo() {
  console.log("Hello!");
}

上一篇
從StackOverflow上學CODING(5)甚麼時候用img或background-image?
下一篇
從StackOverflow上學CODING(7)如何在 JS 檔案中導入另一個 JS 檔案
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言