Function.prototype.mycall=function(context,...args){
context=context||null;
context.fn=this;//this就是当前函数
let res=context.fn(...args);//以context为调用对象
delete context.fn;
return res;
}
Function.prototype.myapply=function(context,args){
context=context||null;
context.fn=this;//this就是当前函数
let res=context.fn(...args);//以context为调用对象
delete context.fn;
return res;
}
Function.prototype.mybind=function(context,...args){
context=context||null;
let fn=this;//this就是当前函数
let fbind=function(...arg_s){
//如果是用函数来new一个对象
if(this instance of fn)return fn.call(context,...args,...arg_s)
//经测试,如果不加以判断的话,this无法指向对象,很容易写乱全局
//如果是正常环境下执行函数
return fn.call(this,...args,...arg_s)
}
let fp=function(){};
fp.prototype=this.prototype;
fbind.prototype=new fp();
return fbind;
}
模拟call、apply、bind
最新推荐文章于 2024-07-23 17:54:41 发布