萬盛學電腦網

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

JavaScript this 關鍵字四大綁定規則與最佳實踐總結

核心觀念:this 在函數被呼叫時決定,而非定義時

同一個函數,依呼叫方式不同,this 指向會改變。四種呼叫模式:

1. 物件方法呼叫 → this 指向該物件

const point = {
    x: 0, y: 0,
    moveTo(dx, dy) {
        this.x += dx;
        this.y += dy;
    }
};
point.moveTo(1, 1); // this === point

2. 普通函數呼叫 → this 指向全域物件(瀏覽器為 window,嚴格模式為 undefined)

function foo() { console.log(this); }
foo(); // 非嚴格模式:window;嚴格模式:undefined

陷阱: 內部函數(巢狀函數)同樣遵循此規則,導致 this 丟失外層物件。

const obj = {
    val: 1,
    outer() {
        function inner() { console.log(this.val); } // this 指向 window/undefined
        inner();
    }
};
obj.outer(); // undefined 或報錯

解決方案: 箭頭函數(無自身 this,捕獲外層)或 const self = this / bind。

3. 建構函數呼叫(new) → this 指向新建立的實例

function Point(x, y) {
    this.x = x;
    this.y = y;
}
const p = new Point(1, 2); // this === p

慣例:建構函數首字母大寫,提醒呼叫者需用 new。

4. call / apply / bind 顯式綁定 → this 指向傳入的第一個參數

function greet(greeting) { console.log(greeting + ', ' + this.name); }
const user = { name: 'Alice' };
greet.call(user, 'Hello');   // Hello, Alice
greet.apply(user, ['Hi']);   // Hi, Alice
const bound = greet.bind(user);
bound('Hey');                // Hey, Alice

進階:判斷函數被如何呼叫

function Foo() {
    if (this instanceof Foo) {
        console.log('建構函數呼叫');
    } else if (this === window) {
        console.log('全域函數呼叫');
    } else {
        console.log('物件方法呼叫,this 指向:', this.constructor.name);
    }
}
Foo();           // 全域函數呼叫
Foo.call({});    // 物件方法呼叫
new Foo();       // 建構函數呼叫

現代最佳實踐

  • 優先使用 箭頭函數 保留外層 this(回呼、事件處理器)。
  • 類別方法若需傳遞當回呼,用 class fields 箭頭函數或建構函數中 this.method = this.method.bind(this)。
  • 避免在非嚴格模式下依賴全域 this,開啟 "use strict" 讓錯誤更早暴露。

總結

掌握四大綁定規則(隱式、隱式丟失、顯式、new),搭配箭頭函數與 bind,即能駕馭 this,寫出可預測、可維護的 JavaScript 程式碼。

copyright © 萬盛學電腦網 all rights reserved