Function.prototype.myCall =function(context){ var context = context || window var context.fn =this// 这个this就是我们使用call的时候前面的函数,相当于上面的对象里面的bar函数 var arg =[].slice.call(arguments,1)// 获取context后面的所有参数 var result = context.fn(...arg) delete context.fn return result } // 使用 var name ='window' var obj ={ name:'chenji' } function test (){ var name ='test' console.log(this.name) } test()//outPut 'window' test.call(obj,12)// outPut 'chenji'
Function.prototype.myApply =function(context){ var context = context || window var context.fn =this// 这个this就是我们使用call的时候前面的函数,相当于上面的对象里面的bar函数 var result // 判断是否有传入第二个参数,apply的第二个参数是数组,有的话就展开 if(arguments[1]){ result = context.fn(..arguments[1]) }else{ result = context.fn() } delete context.fn return result } // 使用 var name ='window' var obj ={ name:'chenji' } function test (){ var name ='test' console.log(this.name) } test()//outPut 'window' test.call(obj,12)// outPut 'chenji'
Function.prototype.bind2=function(context){ if(typeofthis!=="function"){ thrownewError("Function.prototype.bind - what is trying to be bound is not callable"); } varself=this; var arr=Array.prototype.slice.call(arguments,1);//因为第一个参数是作为它运行时的this,所以从第二个开始截取到末尾 returnfunction(){ var binArr=Array.prototype.slice.call(arguments);// 这个时候的arguments是指bind返回的函数传入的参数 returnself.apply(context,arr.concat(binArr)); } }