萬盛學電腦網

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

JavaScript Function.prototype.bind() 深度解析:this 綁定、偽實現與 Polyfill 方案

bind() 核心作用

創建一個新函數,調用時 this 永久綁定到指定對象,並可預設參數 (柯里化)。

基本語法與用法


function.fn.bind(thisArg, arg1, arg2, ...)

// 1. 綁定 this
var obj = {x: 42};
function foo() { console.log(this.x); }
var bound = foo.bind(obj);
bound(); // 42

// 2. 柯里化:預設參數
function add(a, b, c) { return a + b + c; }
var add5 = add.bind(null, 5);     // a=5
var add5_10 = add5.bind(null, 10); // a=5, b=10
console.log(add5_10(3)); // 18 (5+10+3)

// 3. 事件處理器綁定
button.addEventListener('click', handler.bind(this));

// 4. 延遲調用保持上下文
setTimeout(obj.method.bind(obj), 1000);

偽實現原理 (ES5 環境)


if (!Function.prototype.bind) {
    Function.prototype.bind = function(oThis) {
        if (typeof this !== 'function') {
            throw new TypeError('Function.prototype.bind - not callable');
        }
        
        var aArgs = Array.prototype.slice.call(arguments, 1);
        var fToBind = this;
        var fNOP = function() {};
        var fBound = function() {
            // 關鍵:this instanceof fNOP 判斷是否作為構造函數調用 (new bound())
            return fToBind.apply(
                this instanceof fNOP && oThis ? this : oThis,
                aArgs.concat(Array.prototype.slice.call(arguments))
            );
        };
        
        // 維護原型鏈:bound.prototype -> fToBind.prototype
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        
        return fBound;
    };
}

關鍵設計細節解析

  1. 構造函數調用支持:new BoundFn() 時,this 應指向新實例而非綁定對象。this instanceof fNOP 檢測此情況。
  2. 原型鏈繼承:fBound.prototype = new fNOP() 使 bound.prototype.__proto__ === fToBind.prototype,保證 instanceof 正常工作。
  3. 參數合併:綁定時參數 aArgs + 調用時參數 arguments。
  4. length 屬性:標準規定 bound.length = Math.max(fToBind.length - aArgs.length, 0),Polyfill 常忽略。

實戰場景對比

場景舊寫法 (self/that)bind() 寫法
回調函數保持 thisvar that=this; cb(function(){that.method();})cb(this.method.bind(this))
事件監聽器移除el.addEventListener('click', fn); el.removeEventListener('click', fn); // 需保存 fn 引用var bound = fn.bind(this); el.addEventListener('click', bound); el.removeEventListener('click', bound);
柯里化工廠函數function makeAdder(a){return function(b){return a+b;}}add.bind(null, a)
陣列方法傳遞 this[1,2,3].map(function(x){return this.mul(x);}, this)[1,2,3].map(this.mul.bind(this))

箭頭函數 vs bind()


// 箭頭函數:詞法綁定 this (定義時捕獲外層 this)
var obj = {
    value: 42,
    getArrow: () => () => this.value, // 錯誤!this 指向 window/module
    getBind: function() { return function() { return this.value; }.bind(this); }
};

// 正確箭頭函數用法
var obj2 = {
    value: 42,
    getValue: function() {
        return () => this.value; // 內層箭頭函數捕獲外層函數的 this
    }
};

瀏覽器兼容性與 Polyfill 策略

環境支援策略
Chrome 7+ / Firefox 4+ / Safari 5.1.4+ / Edge 12+ / IE 9+原生支援直接使用
IE 6-8不支援引入 ES5-Shim 或上方 Polyfill
Node.js 所有版本原生支援直接使用

現代最佳實踐

  1. 優先用箭頭函數:類方法定義為箭頭函數 method = () => {} 自動綁定實例,無需 bind。
  2. React 類組件:構造函數中 this.handleClick = this.handleClick.bind(this) 或 handleClick = () => {}。
  3. 事件監聽器:綁定後保存引用以便移除,或用 {once: true} 選項。
  4. 避免濫用 bind:每次調用創建新函數,高頻調用 (如 render、map) 有性能開銷,優先考慮箭頭函數或閉包。
copyright © 萬盛學電腦網 all rights reserved