自定义call和apply、bind方法

时间:2020-05-08 14:44:32   收藏:0   阅读:99
call和apply本质上是实现函数调用,即改变this的指向

一、手动实现call方法
Function.prototype.call2=function(object){
let obj =object;
obj.fn = this;
let result;
let args = [...argements].splice(1);
return result =obj.fn(...args)

}
二、重写apply方法
Function.prototype.call2=function(object){
let obj =object;
obj.fn = this;
let result;
let args = [...argements].splice(1);
return result =obj.bn(args)

}

三、手动实现bind方法

Function.prototype.myBind = function(obj,...arg1){ //arg1收集剩余参数
return function (...arg2) { //返回箭头函数, this绑定调用这个方法(myFind)的函数对象
return this.Apply( obj, arg1.concat(arg2) ); // 将参数合并
}
}

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!