手写 call、applay

发布时间 2023-03-30 16:22:02作者: 浅唱年华1920

 

call

Function.prototype.mycall = function(context, ...args) {
  if (this === Function.prototype) {
    return undefined;
  }
  context = context || window;
  const fn = Symbol();
  context[fn] = this; // this就是 调用的函数
  const result = context[fn](...args); // 
  delete context[fn];
  return result;
}

实现逻辑如下,把函数给这个对象,然后通过对象的方式调用,this 就指向这个 对象了

function test(...args) {
  console.log(this.name, ...args);
}
let obj = {
  name: 'lisi'
}
obj.fn = test;
obj.fn(1,2);
apply 只是参数处理不一样
Function.prototype.myapply = function(context, args) {
  if (this === Function.prototype) {
    return undefined;
  }
  context = context || window;
  const fn = Symbol();
  context[fn] = this; // this就是 调用的函数
  const result = context[fn](...args); // 
  delete context[fn];
  return result;
}