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

來源:互聯網
上載者:User

標籤:開頭   參數傳遞   function   ssi   原型   error   concat   span   方法   

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()方法相容處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.