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