萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 函數調用的五種模式完整解析:this 綁定規則與最佳實踐

五種調用模式

JavaScript 函數調用方式決定了函數內部 this 的指向。掌握這五種模式是避免 this 相關 Bug 的關鍵。

1. 函數調用模式(Function Invocation)

function add(a, b) { return this; }
add(1, 2); // 非嚴格模式:window / 全域物件
           // 嚴格模式:undefined
  • 獨立函數呼叫,this 綁定全域物件(非嚴格)或 undefined(嚴格)。
  • 設計缺陷:內部函數無法直接存取外部 this,需用 const self = this 或箭頭函數。

2. 方法調用模式(Method Invocation)

const obj = {
  value: 42,
  getValue() { return this.value; }
};
obj.getValue(); // 42 —— this 綁定 obj
  • 透過物件屬性存取呼叫,this 綁定該物件。
  • 動態綁定:const f = obj.getValue; f() → 變為函數調用模式,this 丟失。

3. 建構子調用模式(Constructor Invocation)

function Person(name) {
  this.name = name;
}
const p = new Person('Alice');
// new 過程:
// 1. 建立空物件 {}
// 2. 物件.__proto__ = Person.prototype
// 3. Person.call(物件, 'Alice') → this 指向新物件
// 4. 回傳新物件(除非構造函數顯式 return 物件)
console.log(p.name); // Alice
  • new 強制建立新物件並綁定 this。
  • 慣例:建構函數首字母大寫,提醒使用者加 new。

4. apply / call 調用模式

function greet(greeting, punctuation) {
  return greeting + ', ' + this.name + punctuation;
}
const user = { name: 'Bob' };

greet.call(user, 'Hello', '!');   // "Hello, Bob!"
greet.apply(user, ['Hi', '?']);   // "Hi, Bob?"
// 箭頭函數無法用 call/apply 改變 this
  • 顯式指定 this 與參數。
  • call 參數列舉,apply 參數陣列。
  • 常用於:借用方法、繼承、函數柯里化、事件處理器綁定。

5. 箭頭函數(Lexical this)

const obj = {
  value: 1,
  regular() { return this.value; },
  arrow: () => this.value
};
obj.regular(); // 1
obj.arrow();   // undefined (全域/模組作用域的 this)
  • 箭頭函數**沒有自己的 this**,捕獲定義時外層作用域的 this。
  • 不可作為建構函數、無 arguments、無 prototype、call/apply/bind 無效。
  • 最適合:回調函數、陣列方法、需保持外層 this 的場景。

this 綁定優先級(由高到低)

  1. new 建構子調用 → 新物件
  2. call/apply/bind 顯式綁定 → 指定物件
  3. 方法調用 obj.fn() → obj
  4. 函數調用 fn() → 全域/undefined
  5. 箭頭函數 → 外層詞法作用域 this

常見陷阱與解決

場景問題解決
事件處理器this 指向 DOM 元素箭頭函數 / bind / e.currentTarget
setTimeout 回調this 丟失箭頭函數 / bind
陣列方法回調this 為 undefined/全域箭頭函數 / 第二參數 thisArg
解構賦值方法const {method} = obj; method() 丟失 thisconst {method: bound} = obj; 或 obj.method()
Class 方法傳遞class 方法提取後 this 丟失constructor 中 bind / Public class fields 箭頭函數

最佳實踐總結

  1. **優先使用箭頭函數**作為回調,自動捕獲外層 this。
  2. **Class 方法**在 constructor 中 this.method = this.method.bind(this) 或使用 Public Class Fields method = () => {}。
  3. **事件綁定**用 addEventListener + 箭頭函數,或 handler.bind(this)。
  4. **庫 API 要求 this**時(如 jQuery 事件處理),用 fn.call(context, ...args) 適配。
  5. **嚴格模式**下函數調用 this = undefined,更早暴露 Bug。
copyright © 萬盛學電腦網 all rights reserved