实现call、apply、bind

 

一、实现myCall

首先,call函数是将this绑定到传入的第一个参数上,其余参数作为调用函数的参数。

func.call(thisArg, arg1, arg2, ...);

那么,分为三步:

  1. 将 this 赋值给 thisArg ,作为它的某个函数属性
  2. 调用这个函数属性
  3. 删除这个属性

方法一:采用数组扩展符

Function.prototype.myCall = function (thisArg, ...arguments) {
  const func = Symbol();
  thisArg[func] = this;
  const res = thisArg[func](...arguments);
  delete thisArg[func];
  return res;
}

方法二:采用eval执行

Function.prototype.myCall = function (context) {
  var thisArg = context[0];
  thisArg.fn = this;
  var evalStr = 'thisArg.fn(';
  for (var i = 1; i < context.length; i++) {
    if (typeof context[i] === 'string') {
      evalStr += `"${context[i]}",`; // 对字符串情况的处理
    } else {
      evalStr += `${context[i]},`;
    }
  }
  var res = eval(evalStr);
  delete thisArg.fn;
  return res;
}

 

二、实现myApply

同myCall,只是参数需以数组的形式。

这里只写一种方法,另一种类似 call。

Function.prototype.myApply = function(thisArg, argArray) {
  const fn = Symbol();
  thisArg[fn] = this;
  const res = thisArg[fn](...argArray);
  delete thisArg[fn];
  return res;
}

三、实现myBind

bind函数返回一个新的函数,例如:

const fun2 = fun1.bind(obj, arg1, arg2);
fun2(arg3, arg4);
// 相当于
fun1.call(obj, arg1, arg2, arg3, arg4);

那么,可以写出:

Function.prototype.myBind = function(thisArg, ...argArray) {
  const self = this; // 这里先将此刻的this暂存起来
  return function(...argArray2) {
    const func = Symbol();
    thisArg[func] = self;
    const res = thisArg[func](...argArray, ...argArray2);
    delete thisArg[func];
    return res;
  }
}

这里只写一种方法,另一种类似 call。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:02
ssob上原来真有BOSS啊
硫蛋蛋:这种也是打工的,只不是是给写字楼房东打工
点赞 评论 收藏
分享
06-10 23:36
已编辑
首都经济贸易大学 C++
点赞 评论 收藏
分享
07-04 21:23
已编辑
东莞城市学院 后端
秋招和春招只收到几个中大厂的笔试,本人比较菜,感觉大厂的笔试太难,算法题不能全部做出来就没过了,但是CVTE和小天才的感觉不是很难,基本上都做出来了,笔试还是挂了。Boss上投了Java后端开发都没有回音,boss上有面试机会都是C#工控软件开发方向的,但是这个方向不太懂,资料又少,面试的表现有点差,现在还是想看看Java这边,面试的时候比较有把握点。想请教一下,这份简历还有什么问题,一直没什么机会,还有什么地方要修改的。
程序员小白条:学历太差,民办和公办,外包还得区分的,这个学历+这个简历,没的办法,除非你有人脉,太难了,这环境,何况你都毕业了,连一段实习都没,肯定没公司会挑选了,没竞争力,开发才招几个人,跟你竞争的可不是二本,三本的人哦,何况你在二本,三本里面也排名不高
投递小天才等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务