- 首先你得知道call是什么
- call能够改变它的调用者的this指向 第一个参数就是想要改变的this 指向, 接下去是一个一个的参数,
- 上图举例子

可以看到console.log出来的 均是我们想要的结果
注意如果没有改变this 指向 因为相当于立即执行函数,所以this会指向window
开始今天的主题
纯净版代码
Function.prototype.mycall=function(){
console.log(arguments);
const args= Array.from(arguments)
const t = args.shift()
const temp=this
console.log(temp);
t.fn=temp //t是{x:10} 也就是要指向的this
console.log(t.fn); //[λ: fn]
console.log(t); //{ x: 10, fn: [λ: fn] }
t.fn(...args)
delete t.fn
}
function fn(a,b){
console.log('a',a);
console.log('b',b);
console.log('this',this);
}
fn.mycall({x:10},10,20)
Function.prototype.mycall=function(){
console.log(arguments);//可以通过arguments 看它的参数 并且能知道这是一个位数组
const args= Array.from(arguments) //通过这个方法将伪数组转化为数组,因为我们要用到数组的方法
// 已知call的第一个参数是this的指向 所以用 shift 把它取出来,这会改变原数组
const t = args.shift() //t就是{x:10} 我要要指向的
// console.log(args) //[ 10, 20 ] //剩下的args 就是我们要传的参数 通过拓展运算符 可以一个一个传进去
//接下去就是 this 了 方法:可以新建一个obj对象 把fn当作obj的一个属性 这样调用fn obj里的this就指向了mycall
const temp=this //先存一下this this 是被fn调用的 所以temp就是 fn
console.log(temp);
t.fn=temp //t是{x:10} 也就是要指向的this
console.log(t.fn); //[λ: fn]
console.log(t); //{ x: 10, fn: [λ: fn] }
t.fn(...args)
delete t.fn
}
function fn(a,b){
console.log('a',a);
console.log('b',b);
console.log('this',this);
}
fn.mycall({x:10},10,20)
本文含有隐藏内容,请 开通VIP 后查看