手写call

26 阅读1分钟
  name: "why",
  age: 18,
};
const foo = function () {
  console.log(this.name);
};

foo.call(person);

Function.prototype.myc = function (context) {
  console.log(this);
  let temp = context;
  temp.abc = this;
  temp.abc();
};

foo.myc(person);

// =======这就是最简单的call,利用显示绑定,但是这里面有几个问题:
Function.prototype.myc1 = function (context) {
  console.log(this);
  let temp = context; //不一定会传参数,所以要判断是不是空
  temp.abc = this; //temp就是person对吧?但是person可能也有abc这个属性,所以这里要搞一个key,这个key是独一无二的存在,就是symbol
  temp.abc(); //这里还有一个问题,增加abc属性后,person就真多了个abc属性,所以调用完要删除一下,
  //有些函数还有返回值,还得给它返回去,
  //既然有返回值,也得有传入参数,也得增加一下函数的接受参数
};
// ====于是我优化一下:
Function.prototype.myc2 = function (context, ...args) {
  //使用...args,把很多参数都放进去,这里肯定是个数组
  console.log(this);
  let temp = context || window; //拿到需要的this
  let key = Symbol("abc"); //这个key就是独一无二的
  temp[key] = this;
  const result = temp[key](...args); // 再把数组解开来,再传进去,
  delete temp[key];
  return result;
};
foo.myc2(person);