IE5以前沒有apply和call的支持,下面的方法兼容版本IEjavascript
if(!Function.prototype.apply){ Function.prototype.apply = function(obj, args){ obj = obj == undefined ? window : Object(obj);//obj能夠是js基本類型 var i = 0, ary = [], str; if(args){ for( len=args.length; i<len; i++ ){ ary[i] = "args[" + i + "]"; } } obj._apply = this; str = 'obj._apply(' + ary.join(',') + ')'; try{ return eval(str); }catch(e){ }finally{ delete obj._apply; } }; } if(!Function.prototype.call){ Function.prototype.call = function(obj){ var i = 1, args = []; for( len=arguments.length; i<len; i++ ){ args[i-1] = arguments[i]; } return this.apply(obj, args); }; }
Function.prototype.es3Bind = function (context) { if (typeof this !== "function") throw new TypeError('what is trying to be bound is not callback'); var self = this; var args = Array.prototype.slice.call(arguments, 1); const fBound = function () { // 獲取函數的參數 var bindArgs = Array.prototype.slice.call(arguments); // 返回函數的執行結果 // 判斷函數是做爲構造函數仍是普通函數 // 構造函數this instanceof fNOP返回true,將綁定函數的this指向該實例,能夠讓實例得到來自綁定函數的值。 // 看成爲普通函數時,this 指向 window,此時結果爲 false,將綁定函數的 this 指向 context return self.apply(this instanceof fNOP ? this: context, args.concat(bindArgs)); } // 建立空函數 var fNOP = function () {}; // fNOP函數的prototype爲綁定函數的prototype fNOP.prototype = this.prototype; // 返回函數的prototype等於fNOP函數的實例實現繼承 fBound.prototype = new fNOP(); // 以上三句至關於Object.create(this.prototype) return fBound; }
//test
function test(a,b){
var re = this.x+a+b
console.log(re)
}java
var f = test.bind({x:3},3);
f(5) //11=3+3+5app
參考連接: https://blog.csdn.net/u010377383/article/details/80646415函數