萬盛學電腦網

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

JavaScript this 綁定機制完整解析:四種調用模式與陷阱避坑指南

this 是 JavaScript 最令人困惑也最核心的機制之一。它的值**在函式被呼叫時決定**,而非定義時。本文系統整理四種標準調用模式、常見陷阱、ES6 箭頭函式解決方案與現代最佳實務。

四大標準調用模式

1. 函式調用模式 → this = window/globalThis

function test() {
    console.log(this); // window (瀏覽器) / global (Node.js)
}
test();

// 嚴格模式下
function testStrict() {
    'use strict';
    console.log(this); // undefined
}
testStrict();

設計缺陷:許多人認為這是語言設計失誤,內部函式也會綁定到全域:

var obj = {
    method: function() {
        console.log(this); // obj
        function inner() {
            console.log(this); // window!非預期
        }
        inner();
    }
};

2. 方法調用模式 → this = 呼叫物件

var obj = {
    name: 'Tom',
    greet: function() {
        console.log(this.name); // 'Tom'
    }
};

obj.greet(); // this 綁定 obj

// 動態綁定特性
var greet = obj.greet;
greet(); // this 變成 window!丟失綁定

3. 建構函式調用模式 → this = 新建立的實例

function Dog(name) {
    this.name = name;     // this 指向新實例
    this.bark = function() {
        console.log(this.name + '汪汪');
    };
}

var wangcai = new Dog('旺財');
wangcai.bark(); // "旺財汪汪"

// 忘記 new 的後果
var oops = Dog('忘記new'); // this 指向 window!
console.log(window.name);  // "忘記new" - 污染全域

防禦寫法:

function Dog(name) {
    if (!(this instanceof Dog)) {
        return new Dog(name); // 自動修正
    }
    this.name = name;
}

4. call/apply/bind 顯式綁定模式

function greet(greeting, punctuation) {
    console.log(greeting + ', ' + this.name + punctuation);
}

var person = { name: 'Tom' };

greet.call(person, 'Hello', '!');    // 參數逐個傳遞
greet.apply(person, ['Hi', '~']);    // 參數用陣列傳遞

var boundGreet = greet.bind(person, 'Hey'); // 回傳新函式,this 永久綁定
boundGreet('?'); // "Hey, Tom?"

現代環境:事件監聽器中的 this

// 現代標準:addEventListener
element.addEventListener('click', function(e) {
    console.log(this); // 觸發事件的元素 (currentTarget)
    console.log(e.target); // 實際被點擊元素
});

// 箭頭函式:繼承外層 this
element.addEventListener('click', (e) => {
    console.log(this); // 外層 this (通常是 window 或類別實例)
    console.log(e.currentTarget); // 取得元素請用 e.currentTarget
});

IE 歷史差異:attachEvent

// IE8- 專有
element.attachEvent('onclick', function() {
    console.log(this); // window!非元素
});
// 這是導致 jQuery 內部需大量修正 this 的主因

六大經典陷阱與解決方案

陷阱 1:回調函式丟失 this

var obj = {
    value: 42,
    getValue: function() { return this.value; }
};

setTimeout(obj.getValue, 100); // undefined - this 變 window

// 解決方案
setTimeout(obj.getValue.bind(obj), 100);        // bind
setTimeout(() => obj.getValue(), 100);          // 箭頭函式
setTimeout(function() { obj.getValue(); }, 100); // 閉包

陷阱 2:物件方法作為回調傳遞

$('#btn').click(obj.handler); // jQuery: this 會被綁定為元素

// 解決:$.proxy 或 bind
$('#btn').click($.proxy(obj.handler, obj));
$('#btn').click(obj.handler.bind(obj));

陷阱 3:解構賦值丟失方法綁定

var { method } = obj;
method(); // this = undefined (嚴格模式) 或 window

// 解決
var { method: boundMethod } = obj; // 不行
var boundMethod = obj.method.bind(obj); // 正確

陷阱 4:類別中事件處理器

class Component {
    constructor() {
        this.value = 1;
        // ❌ 錯誤:每次 render 建立新函式,無法移除監聽
        this.el.addEventListener('click', () => this.handleClick()); 
        
        // ✅ 正確:建構函式建立一次 bound 函式
        this.boundHandleClick = this.handleClick.bind(this);
        this.el.addEventListener('click', this.boundHandleClick);
    }
    handleClick() { console.log(this.value); }
    destroy() {
        this.el.removeEventListener('click', this.boundHandleClick);
    }
}

陷阱 5:forEach/map 回調的 this

[1,2,3].forEach(function(x) {
    console.log(this); // window/undefined
}, thisArg); // 第 2 參數指定 this

// 現代:箭頭函式自動捕獲外層 this
[1,2,3].forEach(x => console.log(this));

陷阱 6:bind 多次無效

function fn() { console.log(this.a); }
var obj1 = { a: 1 };
var obj2 = { a: 2 };

var bound = fn.bind(obj1).bind(obj2);
bound(); // 1 - 第一次 bind 勝出,後續 bind 無效

ES6 箭頭函式:詞法 this 徹底解決

var obj = {
    value: 42,
    // 箭頭函式沒有自己的 this,繼承外層 (此處為全域/模組)
    arrow: () => console.log(this.value), 
    
    // 一般函式有自己的 this
    method() {
        console.log(this.value); // 42
        
        // 內部箭頭函式捕獲 method 的 this
        setTimeout(() => console.log(this.value), 100); // 42
    }
};

總結:this 判斷決策樹

  1. **箭頭函式**?→ 繼承外層詞法作用域 this
  2. **new 呼叫**?→ this = 新實例
  3. **call/apply/bind**?→ this = 指定物件
  4. **物件方法呼叫** (obj.fn())?→ this = obj
  5. **普通函式呼叫**?→ this = window/globalThis (非嚴格) / undefined (嚴格)

掌握 this 機制,是從「能寫出跑的代碼」進階到「寫出健壯、可維護、可測試代碼」的關鍵門檻。

copyright © 萬盛學電腦網 all rights reserved