1. 程式人生 > >javascript對象bind()方法兼容處理

javascript對象bind()方法兼容處理

eof ava not possible close 方法 internal ceo con

bind() 函數在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運行。你可以部份地在腳本開頭加入以下代碼,就能使它運作,讓不支持的瀏覽器也能使用 bind() 功能

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw
new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, // 此處的 this 指向目標函數 fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof
fNOP ? this // 此處 this 為 調用 new obj() 時所生成的 obj 本身 : oThis || this, // 若 oThis 無效則將 fBound 綁定到 this // 將通過 bind 傳遞的參數和調用時傳遞的參數進行合並, 並作為最終的參數傳遞 aArgs.concat(Array.prototype.slice.call(arguments))); }; // 將目標函數的原型對象拷貝到新函數中,因為目標函數有可能被當作構造函數使用 fNOP.prototype = this
.prototype; fBound.prototype = new fNOP(); return fBound; }; }

javascript對象bind()方法兼容處理