FE Interview Hub
JavaScript 基礎

箭頭函式 (arrow function) 和一般函式的差別是什麼

AI 練習作答

主要差異

1. this 的綁定

這是最關鍵的差別。

  • 一般函式this呼叫方式決定(動態綁定)
  • 箭頭函式this定義時的外層作用域決定(靜態綁定,繼承 lexical this
const obj = {
  name: 'Alice',
  greetRegular: function() {
    setTimeout(function() {
      console.log(this.name); // undefined(this 指向全域或 undefined in strict mode)
    }, 100);
  },
  greetArrow: function() {
    setTimeout(() => {
      console.log(this.name); // 'Alice'(繼承外層的 this)
    }, 100);
  }
};

2. 不能作為建構函式

箭頭函式無法用 new 呼叫,否則會拋出 TypeError

const Foo = () => {};
new Foo(); // TypeError: Foo is not a constructor

3. 沒有 arguments 物件

function regular() {
  console.log(arguments); // Arguments 物件
}

const arrow = () => {
  console.log(arguments); // ReferenceError 或外層的 arguments
};

4. 沒有 prototype 屬性

function Foo() {}
console.log(Foo.prototype); // { constructor: Foo }

const Bar = () => {};
console.log(Bar.prototype); // undefined

5. 不能用作 Generator

箭頭函式不能使用 yield

何時使用

情境 推薦
需要動態 this(物件方法、建構函式) 一般函式
Callback、事件監聽、陣列方法 箭頭函式
需要 arguments 物件 一般函式

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分