箭頭函式運算式(Arrow Function Expression)

介紹

是 JavaScript 中的一種簡化函式語法,使用 => 來定義函式。
相較於傳統函式(function),箭頭函式提供語法簡潔的寫法,並且 this 的綁定行為有所不同。


語法

基本語法

// 箭頭函式:
const sum = (a, b) => {
  return a + b;
};
console.log(sum(2, 3)); // 5

// 傳統函式:
const sumTraditional = function(a, b) {
  return a + b;
};

簡化語法(單一運算式可省略大括號與 return)

const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5

單一參數可省略括號

const square = x => x * x;
console.log(square(4)); // 16

無參數時需保留括號

const greet = () => console.log("Hello!");
greet(); // Hello!

this 的綁定行為

箭頭函式的 this 是靜態綁定的,會繼承外層作用域的 this,而非根據執行時上下文決定。

function Person(name) {
  this.name = name;
  setTimeout(() => {
    console.log(this.name); // "Jack",this 綁定自 Person 函式作用域
  }, 1000);
}

const person = new Person("Jack");

與傳統函式比較:

function Person(name) {
  this.name = name;
  setTimeout(function() {
    console.log(this.name); // undefined,this 綁定到 setTimeout 的執行上下文(通常是 global 或 undefined)
  }, 1000);
}

const person = new Person("Jack");

arguments 在箭頭函式中的使用

箭頭函式不具備自己的 arguments,會繼承外層普通函式的 arguments

function test() {
  const arrowFunc = () => console.log(arguments);
  arrowFunc();
}

test(1, 2, 3); // ✅ [1, 2, 3]

如果箭頭函式不是包在普通函式中,直接使用 arguments 會報錯

const arrowFunc = () => console.log(arguments);
arrowFunc(1, 2, 3); 
// ❌ Uncaught ReferenceError: arguments is not defined

解法:使用展開運算符 ...args 來取得參數列表

const arrowFunc = (...args) => console.log(args);
arrowFunc(1, 2, 3); // ✅ [1, 2, 3]

函式的內建變數比較

特性 普通函式 (function) 箭頭函式 (=>)
arguments ✅ 有 ❌ 無
函式參數 (a, b) ✅ 有 ✅ 有
...args 展開運算符 ✅ 有 ✅ 有

arguments 範例(普通函式)

function normalFunc(a, b) {
  console.log(arguments);
}
normalFunc(2, 3); 
// ✅ [Arguments] { '0': 2, '1': 3 }

注意事項

  • 箭頭函式無法用作建構子(constructor),使用 new 調用會報錯。
  • 箭頭函式無法使用 yield,因此不能用作 Generator 函式。
  • 箭頭函式常用於:短小函式、Array 操作中的 callback(如 map, filter 等)、避免 this 混淆的非同步場景。

參考資料