call & apply实现
let a = {
y:'zjy',
x(m,n){
console.log(this.y,m,n)
}
}
let b = {
y:'lyn'
}
a.x.call(b,1,2) //lyn 1 2
a.x.apply(b,[1,2]) //lyn 1 2
call
Function.prototype.myCall = function(obj,...args){
obj = obj ? Object(obj) : window
obj.fn = this
let res = obj.fn(...args)//隐式绑定
delete obj.fn
return res
}
apply
Function.prototype.myApply = function(obj,args){
obj = obj ? Object(obj) : window
obj.fn = this
let res = obj.fn(...args)//隐式绑定
delete obj.fn
return res
}
注:为什么参数的第一个值不默认设置为window,防止实参为null,undefined
以自己现在的努力程度,还没有资格和别人拼天赋

浙公网安备 33010602011771号