2022-09-06【自定义call函数】

197 阅读1分钟

首先看一下call的使用方法

const b = function (){
console.log(this.name)//A
}
const a = {
name:"A"
}
b.call(a)
  • 执行了b函数
  • b的this指向了a
  • 如果a调用了这个b函数,b中的this就指向了a 根据以上思路,我们尝试手写一个call函数

Function.prototype.myCall = function(context = window, ...args) {
  if (typeof this !== "function") {
    throw new Error('type error')
  }
  // this-->b函数  context--> a对象  args--> 传递过来的参数
  //想要改变b函数的this指向,只需要实现a.b()即可
  // 在context上添加fn属性,并赋值为this,即b函数
   context.fn = this; 

  
  // 绑定参数 并执行函数
  //此时fn是由context执行的即a对象,而fn即为b函数,所以它的额this指向了context即a对象
  
  let result =  context.fn(...args);
  // 清除定义的this 不删除会导致context属性越来越多
  delete context['fn'];

  // 返回结果 
  return result;
};