萬盛學電腦網

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

JavaScript call、apply、bind 深度解析:改變 this 指向與實現繼承

call() — 參數列表形式


function add(a, b) { alert(a + b); }
function sub(a, b) { alert(a - b); }

add.call(sub, 1, 3); // 4 —— 將 add 的邏輯套用到 sub 上下文(此處 sub 只是作為 this,實際執行 add 代碼)

語法:func.call(thisArg, arg1, arg2, ...)

apply() — 參數陣列形式


add.apply(sub, [1, 3]); // 4 —— 唯一差別:第二參數為陣列/類陣列

核心用途一:改變 this 指向


function showThis() { alert(this); }
showThis();           // window
showThis.call();      // window
showThis.call("abc"); // "abc" (字串被包裝為 String 物件)

核心用途二:實現繼承(建構函數借用)


function Animal(name) {
    this.name = name;
    this.showName = function() { alert(this.name); };
}

function Cat(name) {
    Animal.call(this, name); // 繼承 Animal 實例屬性/方法
}

var cat = new Cat("Black Cat");
cat.showName(); // "Black Cat"

bind() — 返回綁定 this 的新函數 (ES5)


var boundShow = cat.showName.bind(cat);
setTimeout(boundShow, 1000); // 1 秒後正確輸出 "Black Cat"

// 手動實現 bind(兼容舊環境)
if (!Function.prototype.bind) {
    Function.prototype.bind = function(context) {
        var fn = this, args = Array.prototype.slice.call(arguments, 1);
        return function() {
            return fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));
        };
    };
}

實戰場景:事件處理器綁定實例 this


class MyClass {
    constructor() {
        this.el = document.createElement('div');
        // 使用 bind 確保 onClick 內的 this 指向 MyClass 實例
        this.el.addEventListener('click', this.onClick.bind(this));
    }
    onClick(e) { console.log(this === myInstance); // true }
}

借用陣列方法處理類陣列


function demo() {
    // arguments 是類陣列,無 slice 方法
    var args = Array.prototype.slice.call(arguments); // 轉為真陣列
    // ES6 更簡單:const args = [...arguments]; 或 Array.from(arguments);
}

總結比較

方法參數形式回傳值典型用途
call展開列表函數執行結果立即調用、繼承借用、借用方法
apply陣列/類陣列函數執行結果參數已在陣列中、Math.max.apply(null, arr)
bind展開列表新函數(永久綁定 this)事件回調、延遲調用、柯里化
copyright © 萬盛學電腦網 all rights reserved