重写call
三个功能:获取fn参数、改变this(重难点)、获取返回值
改变this指向技巧:使用t.fn,将要执行的fn作为t对象的属性,如此一来 fn中的this将指向t
//手写call源码
Function.prototype.myCall = function(){
const args = Array.from(arguments)
//改变this的值
const t = args.shift()
const self = this//保存this指向到self变量中,此处的this为调用者fn
t.fn = self //此处可理解创建self变量的意义,为了指向同一块地址
//获取fn参数 并传入fn执行
const res = t.fn(...args)//将第二位开始后的参数作为fn参数传入并执行
delete t.fn //t.fn只是为了便于改变this指向的技巧,在执行完fn后应该删除掉其捆绑关系
//获取返回值
//只需声明res接收fn调用后的返回值即可return返回值
return res
}
//fn函数
function fn(a,b){
console.log('a',a)
console.log('b',b)
console.log('this',this)
return 'hello'
}
//调用myCall
const res = fn.myCall({npc:18},20,30)
console.log('res',res)