JavaScript 函數是「一等公民」,調用方式決定了 this 指向、參數傳遞、作用域鏈等核心行為。本文系統梳理五種調用模式,透過對比幫你徹底搞懂 this 綁定規則。
| 模式 | 語法 | this 指向 | 參數形式 | 典型場景 |
|---|---|---|---|---|
| 1. 直接調用 | func(arg1, arg2) | 非嚴格模式:window/globalThis;嚴格模式:undefined | 列表 | 普通函數、工具函數 |
| 2. 方法調用 | obj.method(arg1, arg2) | 調用者 obj | 列表 | 對象方法、類實例方法 |
| 3. 建構器調用 | new Func(arg1, arg2) | 新創建的實例對象 | 列表 | 類實例化、工廠函數 |
| 4. 間接調用 | func.call(ctx, arg1, arg2)func.apply(ctx, [arg1, arg2]) | 指定的 ctx(null/undefined → 全域) | 列表 / 陣列/類陣列 | 借用方法、顯式綁定 this |
| 5. 綁定調用 | func.bind(ctx, arg1, arg2)() | 永久綁定 ctx,new 時例外 | 預設參數 + 調用時參數 | 回調傳遞、事件處理、偏函數 |
func()function foo() { console.log(this); }
foo(); // 非嚴格:window / 嚴格:undefined
// 陷阱:回調中丟失 this
var obj = {
value: 42,
method: function () { console.log(this.value); }
};
setTimeout(obj.method, 100); // 非嚴格輸出 undefined (this=window, window.value=undefined)
// 模塊模式:創建私有作用域
var Counter = (function () {
var count = 0; // 私有變量
return {
inc: function () { return ++count; },
dec: function () { return --count; }
};
})();
Counter.inc(); // 1
Counter.inc(); // 2
// 參數化 IIFE:傳入全域、庫引用
(function (global, $, undefined) {
// 內部用 $ 安全引用 jQuery
global.MyPlugin = { ... };
})(window, jQuery);
bind():硬綁定 thisvar obj = { x: 10 };
function show() { console.log(this.x); }
var bound = show.bind(obj);
bound(); // 10
// 偏函數應用:預設參數
function greet(greeting, name) { console.log(greeting + ', ' + name); }
var sayHi = greet.bind(null, 'Hi');
sayHi('Alice'); // Hi, Alice
sayHi('Bob'); // Hi, Bob
// 事件處理器綁定(經典用法)
button.addEventListener('click', handler.bind(componentInstance));
// ⚠️ bind 返回新函數,無法用 removeEventListener 移除(需保存引用)
var boundHandler = handler.bind(this);
el.addEventListener('click', boundHandler);
el.removeEventListener('click', boundHandler); // 正確
call() vs apply():雙生子function sum(a, b, c) { return a + b + c; }
sum.call(null, 1, 2, 3); // 6,參數列表
sum.apply(null, [1, 2, 3]); // 6,陣列/類陣列
// 經典用例:類陣列轉陣列
var argsArray = Array.prototype.slice.call(arguments);
// 現代寫法
var argsArray = [...arguments]; // 或 Array.from(arguments)
// 借用數組方法處理字符串/類陣列
var max = Math.max.apply(null, [1, 5, 3, 9]); // 9
// 現代
var max = Math.max(...[1, 5, 3, 9]);
this(第六種模式)var obj = {
value: 42,
regular: function () { console.log(this.value); },
arrow: () => console.log(this.value) // 詞法作用域:外層 this (window/module)
};
obj.regular(); // 42
obj.arrow(); // undefined (或模塊頂層 this)
// 箭頭函數無法用 call/apply/bind 改變 this
obj.arrow.call({value: 99}); // 仍是 undefined
this 管理class UIComponent {
constructor(name) { this.name = name; }
// ❌ 錯誤:直接傳遞方法,this 丟失
// button.onclick = this.handleClick;
// ✅ 方案 A:bind(需保存引用以便移除)
// this.boundClick = this.handleClick.bind(this);
// button.addEventListener('click', this.boundClick);
// ✅ 方案 B:箭頭函數屬性(實例綁定,自動綁定 this)
handleClick = (e) => {
console.log(this.name, 'clicked', e.target);
};
// ✅ 方案 C:綁定在構造器
// constructor() { this.handleClick = this.handleClick.bind(this); }
}
// 1. 類陣列借用 forEach
Array.prototype.forEach.call(document.querySelectorAll('li'), function (li) {
li.style.color = 'red';
});
// 2. 物件借用 hasOwnProperty(防原型污染)
var obj = Object.create(null);
obj.custom = 1;
Object.prototype.hasOwnProperty.call(obj, 'custom'); // true
// 3. arguments 借用 slice
function fn() {
var args = Array.prototype.slice.call(arguments);
// 或現代
var args = [...arguments];
}
'use strict';
function foo() { console.log(this); }
foo(); // undefined (而非 window)
// call/apply/bind 傳 null/undefined → this 為 null/undefined(非嚴格會轉全域)
foo.call(null); // null
foo.apply(undefined); // undefined
掌握五大調用模式(+ 箭頭函數)的 this 綁定規則,是寫出可預測、可維護 JS 代碼的關鍵。口訣:
誰調用,this 指誰(方法調用)
new 創建實例,this 指實例(建構器)
call/apply/bind 手動指定(顯式綁定)
箭頭函數看外層(詞法綁定)
直接調用看嚴格(默認全域/undefined)