//手写bind
Function.prototype.myBind=function(ctx,...args){
console.log(this,'这里的this表示函数的调用者')
const fns=this;
return function(...restArgs){
//当前函数是否通过new调用,通过new.target方法判断
if(new.target){
return new fn(ctx,[...args,...restArgs])
}
//如果是普通函数,不管函数有没有返回值,调用会返回undefind,所以进行如下处理
return fns.apply(ctx,[...args,...restArgs])
}
}
function fn(a,b,c,d){
console.log(this) //返回[Number: 1]
console.log(a,b,c,d) //返回2 2 3 4
}
//官方的bind除了第一个参数,后面的参数返回为剩余参数,第一个参数表示this,所以上述函数里面打印的this是1
//使用手写的bind
let newfn=fn.myBind(1,2)
let r1=newfn(2,3,4) //普通调用
let r2=new newfn(2,3,4) //通过new调用
console.log(r1,'普通调用')
console.log(r2,'通过new调用')
//使用官方的bind
let newfn2=fn.bind(1,2)
let old1=newfn(2,3,4) //普通调用
let old2=new newfn(2,3,4) //通过new调用
console.log(old1,'bind普通调用');
console.log(old2,'bind通过new调用');
//最后结果经打印,一致
08-09
1882

08-18
707
