萬盛學電腦網

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

JavaScript 中正確使用 bind 方法綁定 this 上下文

問題背景

JavaScript 中函式的 this 由呼叫方式決定。直接引用方法會導致上下文丟失:

var log = console.log;
log('info...'); // TypeError: Illegal invocation
// 因為 log 現在以函式形式呼叫,this 指向 window,非 console

bind 解決方案

var log = console.log.bind(console);
log('info...'); // 正常運作,this 永遠綁定為 console

bind 回傳新函式,內部透過 apply 強制指定 this,經典閉包應用。

IE8 及以下 Polyfill

if (!Function.prototype.bind) {
  Function.prototype.bind = function(context) {
    var fn = this;
    return function() {
      return fn.apply(context, arguments);
    };
  };
}

核心:閉包保存 fn(原函式)與 context(目標 this),呼叫時以 apply 套用。

進階用法

  • 預設參數:bind(context, arg1, arg2) 可預先綁定參數(偏函式應用)。
  • 事件監聽器:element.addEventListener('click', handler.bind(this)) 確保處理器內 this 指向元件實例。
  • 陣列方法借用:Array.prototype.slice.bind(arguments) 將類陣列轉真陣列。

注意事項

  1. bind 回傳新函式,**原函式不變**;多次 bind 會疊加包裹,效能微損。
  2. 箭頭函式**沒有自己的 this**,bind 無效,勿對箭頭函式使用。
  3. 建構函式經 bind 後仍可 new,this 指向新實例,但原型鏈保持不變(ES2015 規範)。
copyright © 萬盛學電腦網 all rights reserved