call,apply,bind都是改变this指向的问题
将方法中的this指向call中第一个参数,当第一个参数为null、undefined时,默认指向window;
call中第一个参数之后是要传递给方法的参数列表。
apply与call相似,不同之处在于传递给方法的参数形式不一致。apply传递给方法的参数是数组的形式。
call和apply在改变方法的this指向时,会同时执行方法;
而bind不会执行方法,而是返回改变this指向后的新方法。
手写call代码
function myCall(fn,thisObj,...args){
thisObj = thisObj?thisObj:window
thisObj.fn = fn
let result = thisObj.fn(...args)
delete thisObj.fn
return result
}
手写apply代码
args:是一个数组
function myApply(fn,thisObj,args){
thisObj = thisObj?thisObj:window
thisObj.fn = fn
let result = thisObj.fn(...args)
delete thisObj.fn
return result
}
手写Bind代码
function myBind(fn,thisObj,...args){
return function(...args1){
return fn.call(thisObj,...args,...args1)
}
}