萬盛學電腦網

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

JavaScript 函式四種調用模式與 this 綁定機制深度解析

JavaScript 函式是一等物件,擁有四種調用模式,每種模式下 this 綁定規則不同。理解這機制是掌握 JS 物件導向與函數式程式設計的關鍵。

四種調用模式總覽

模式語法this 綁定典型場景
方法調用obj.method()調用物件 obj物件導向、原型鏈
函式調用func()全域物件(非嚴格)/ undefined(嚴格)工具函式、回調
建構子調用new Func()新建立的實例物件類別實例化、原型繼承
Apply/Call/Bindfunc.call(ctx, ...)指定的 ctx 物件借用方法、柯里化、綁定回調

1. 方法調用模式

const myObject = {
    name: 'myObject',
    value: 0,
    increment(num) {
        this.value += typeof num === 'number' ? num : 0;
        return this; // 鏈式調用
    },
    toString() {
        return `[Object: ${this.name} {value: ${this.value}}]`;
    }
};

console.log(myObject.increment(10).increment(20).toString());
// [Object: myObject {value: 30}]

2. 函式調用模式與 this 陷阱

const myObject = {
    value: 0,
    getInfo() {
        // 內部函式 this 指向全域/undefined
        const inner = function() {
            console.log(this); // window 或 undefined
            return this.value; // 無法存取外層 this.value
        };
        return inner();
    }
};

// 解法一:儲存 this 參考(傳統)
getInfoFixed() {
    const self = this;
    const inner = function() {
        return self.value; // 透過 closure 存取
    };
    return inner();
}

// 解法二:箭頭函式(ES6+ 推薦)
getInfoArrow() {
    const inner = () => this.value; // 箭頭函式沒有自己的 this,繼承外層
    return inner();
}

// 解法三:bind 綁定
getInfoBind() {
    const inner = function() { return this.value; }.bind(this);
    return inner();
}

3. 建構子調用模式

function MyObject(name) {
    this.name = name || 'MyObject';
    this.value = 0;
    this.increment = function(num) {
        this.value += typeof num === 'number' ? num : 0;
    };
    this.toString = function() {
        return `[Object: ${this.name} {value: ${this.value}}]`;
    };
}

// 原型方法共享
MyObject.prototype.getInfo = function() {
    return this.toString();
};

const obj1 = new MyObject('Obj1');
obj1.increment(10);
console.log(obj1.value); // 10

const obj2 = new MyObject('Obj2');
obj2.increment(20);
console.log(obj2.value); // 20

console.log(obj1.getInfo()); // [Object: Obj1 {value: 10}]

4. Apply / Call / Bind 調用模式

function MyObject(name) {
    this.name = name || 'MyObject';
    this.value = 0;
}

function getInfo() {
    return `[Object: ${this.name} {value: ${this.value}}]`;
}

const obj = new MyObject('TestObj');
obj.value = 42;

// call: 參數逐個傳遞
console.log(getInfo.call(obj)); // [Object: TestObj {value: 42}]

// apply: 參數陣列傳遞
function sum(a, b, c) { return a + b + c; }
console.log(sum.apply(null, [1, 2, 3])); // 6

// bind: 回傳綁定 this 的新函式
const boundGetInfo = getInfo.bind(obj);
console.log(boundGetInfo()); // [Object: TestObj {value: 42}]

// 實務:事件處理器綁定
class Component {
    constructor() {
        this.count = 0;
        // 錯誤:this 指向觸發元素
        // button.addEventListener('click', this.handleClick);
        // 正確:bind 綁定實例
        button.addEventListener('click', this.handleClick.bind(this));
        // 或箭頭函式屬性
        // this.handleClick = () => { ... }
    }
    handleClick() { this.count++; }
}

arguments 物件與 rest 參數

function func(a, b) {
    console.log('a:', a);        // 1
    console.log('b:', b);        // 2
    console.log('arguments:', arguments); // [1, 2, 3, 4, 5] 類陣列
    console.log('arguments.length:', arguments.length); // 5
    
    // arguments 不是陣列,但可迭代
    for (const arg of arguments) console.log(arg);
    
    // 轉真正陣列
    const argsArray = [...arguments];
    const argsArray2 = Array.from(arguments);
    
    // 遞迴呼叫自身(arguments.callee 在嚴格模式禁用)
    // 現代寫法:具名函式表達式
    const factorial = function fact(n) {
        return n <= 1 ? 1 : n * fact(n - 1);
    };
}

func(1, 2, 3, 4, 5);

函式 length 屬性

function foo(a, b, c = 10) {}
console.log(foo.length); // 2(只計算預設值前的參數)

// arguments.length 是實際傳入參數數
function bar(a, b) {}
bar(1, 2, 3); // arguments.length = 3, bar.length = 2

總結:this 綁定優先順序

  1. new 綁定:new Fn() → this = 新實例
  2. 顯式綁定:call/apply/bind → this = 指定物件
  3. 隱式綁定:obj.fn() → this = obj
  4. 預設綁定:fn() → this = globalThis (非嚴格) / undefined (嚴格)
  5. 箭頭函式:無自己的 this,繼承外層詞法作用域的 this

實務建議

  • 類別方法用箭頭函式屬性或建構子內 bind
  • 回調函式傳遞時用 fn.bind(this) 或箭頭函式包裝
  • 避免在函式調用模式依賴 this,改用參數傳遞
  • 使用 eslint 規則 no-invalid-this、prefer-arrow-callback 輔助檢查
copyright © 萬盛學電腦網 all rights reserved