萬盛學電腦網

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

JavaScript 巢狀函數 this 綁定丟失問題與解決方案

問題現場

const obj = {
    method() {
        console.log(this === obj); // true
        function inner() {
            console.log(this === obj); // false!嚴格模式下 undefined,非嚴格下 window
        }
        inner();
    }
};
obj.method();

**原因:** 普通函數的 this 由**呼叫方式**決定,而非定義位置。inner() 為普通呼叫,this 指向全域物件(或嚴格模式下 undefined)。

解決方案對比

1. 箭頭函數(ES2015,最推薦)

const obj = {
    method() {
        console.log(this === obj); // true
        const inner = () => {
            console.log(this === obj); // true!箭頭函數沒有自己的 this,繼承外層詞法作用域的 this
        };
        inner();
    }
};

2. 變數暫存(傳統寫法)

const obj = {
    method() {
        const self = this; // 或 that、_this
        function inner() {
            console.log(self === obj); // true
        }
        inner();
    }
};

3. bind/call/apply 綁定

function inner() {
    console.log(this === obj);
}
inner.call(obj);      // 立即呼叫並綁定
inner.bind(obj)();    // 返回綁定後的新函數再呼叫

4. 物件方法簡寫 + 箭頭函數屬性(Class/物件字面量)

class MyClass {
    method() {
        console.log(this instanceof MyClass); // true
        const inner = () => {
            console.log(this instanceof MyClass); // true
        };
        inner();
    }
}

// 或物件字面量
const obj = {
    method() {
        const inner = () => { /* ... */ };
        inner();
    }
};

進階:事件回調中的 this 丟失

class UI {
    constructor() {
        this.count = 0;
        // ❌ 錯誤:click 時 this 指向 button 元素
        // document.querySelector("button").addEventListener("click", this.handleClick);

        // ✅ 正確:箭頭函數綁定實例 this
        document.querySelector("button").addEventListener("click", () => this.handleClick());

        // ✅ 正確:bind
        // document.querySelector("button").addEventListener("click", this.handleClick.bind(this));
    }
    handleClick() {
        console.log(this.count++); // 正確訪問實例屬性
    }
}

總結選擇指南

場景推薦方案
物件/類別內部巢狀函數箭頭函數
需動態綁定不同 thisbind / call / apply
舊環境無 Babel/Transpileconst self = this
事件監聽器箭頭函數或 bind(this)
回調函數(如 setTimeout)箭頭函數
copyright © 萬盛學電腦網 all rights reserved