利用洗个脚的时间,来一起手搓Function.prototype.call

82 阅读1分钟

题目 实现Function.prototype.call 描述 Function.prototype.call可以用来很方便的修改函数的this

你能实现一个myCall来模拟Function.prototype.call吗?

根据最新的 ECMAScript specthisArg 不会被类型转换,在 Strict Mode下也不会被更改为window。

你的代码需要遵从上述逻辑,实现非strict mode的情况。

Function.prototype.call/apply/bind和 Reflect.apply 可以了解,但请不要在这里使用。

答案

Function.prototype.mycall = function (thisArg, ...args) {
  //获取调用的函数
  const target = this;
  const flag = Symbol();
  //undefined || null 应赋值为globalWindow,其它类型应尝试使用Object(thisArg);
  // thisArg = Object(thisArg || globalThis); 0 和 ""也会被改成window
  if(thisArg === null || thisArg === undefined){
      thisArg = globalThis;
  }else{
     thisArg = Object(thisArg);
  }
  //利用this特性:对于普通函数来说,谁调用this就指向谁。
  thisArg[flag] = target;
  const res = thisArg[flag](...args);
  //删除flag属性。
  delete thisArg[flag];
  return res;
}

资料 juejin.cn/post/705633…