萬盛學電腦網

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

ECMAScript 5 bind() 方法深度解析:原理、兼容性與實戰應用

bind() 核心作用

bind() 與 call()/apply() 一樣能改變 this 指向,但 **不立即執行**,而是返回一個 **新函數**(綁定後的函數),調用新函數時 this 永久綁定為指定對象。

基礎示例

var obj = { a: 1, b: 2, getCount(c, d) { return this.a + this.b + c + d; } };
window.a = window.b = 0;

console.log(obj.getCount(3, 4)); // 10 (this=obj)
var func = obj.getCount;
console.log(func(3, 4));         // 7  (this=window, a=b=0)

// bind 綁定 this
var bound = obj.getCount.bind(obj);
console.log(bound(3, 4));        // 10 (this 永久綁定為 obj)

bind() 參數詳解

func.bind(thisArg, arg1, arg2, ...)
  • thisArg:新函數運行時的 this 值。
  • arg1, arg2...:預設參數,調用新函數時會插入到實參前面(偏函數應用)。

偏函數應用示例

function add(a, b, c) { return a + b + c; }
var add10 = add.bind(null, 10);     // 固定第一參數為 10
console.log(add10(2, 3));           // 15 (10+2+3)
console.log(add10(5, 5));           // 20 (10+5+5)

兼容性 Polyfill(IE6-8 不支持)

if (!Function.prototype.bind) {
    Function.prototype.bind = function(context) {
        var self = this; // 原函數
        var args = Array.prototype.slice.call(arguments, 1); // 預設參數
        return function() {
            // 合併預設參數與調用時參數
            return self.apply(context, args.concat(Array.prototype.slice.call(arguments)));
        };
    };
}

核心:閉包保存 self(原函數)和 args(預設參數),返回新函數內部用 apply 執行。

bind vs call/apply 核心差異

特性bindcall / apply
執行時機返回新函數,**延後執行****立即執行**
返回值新函數原函數執行結果
參數傳遞預設參數 + 調用時參數僅調用時參數
this 綁定永久綁定單次調用綁定

實戰應用場景

  1. 事件處理器綁定實例方法:
    class Handler {
        constructor() { this.count = 0; }
        click() { console.log(++this.count); }
    }
    const h = new Handler();
    btn.addEventListener('click', h.click.bind(h)); // this 永遠指向 h
  2. 回調函數保持上下文:
    setTimeout(obj.method.bind(obj), 1000);
    [1,2,3].map(func.bind(context));
  3. 函數柯里化/預設參數:
    const log = console.log.bind(console, '[DEBUG]');
    log('message'); // [DEBUG] message
  4. 借用方法:
    const slice = Array.prototype.slice.bind(arguments); // 類數組轉數組

箭頭函數時代的 bind

箭頭函數無自身 this,捕獲外層 this,**無法被 bind 改變**;

const arrow = () => this;
arrow.bind({a:1})(); // 仍指向外層 this,bind 無效

因此箭頭函數天然適合作為回調,無需 bind。

copyright © 萬盛學電腦網 all rights reserved