標籤:開頭 參數傳遞 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()方法相容處理