2022-09-05【手写简易版bind函数】

129 阅读1分钟

首先来看一下bind的使用方法

a.bind(b,arg1,arg2)

可以反过来推导出,bind函数的三个核心点

  1. 改变了this指向
  2. 第一个参数是this指向的值,剩余的是函数接收的参数
  3. 返回了一个函数(返回调用者本身) 从这几点入手我们还原一下bind的实现
Function.prototype.myBind = function(){
const that = this;//看上面的例子,this指向a
const args = Array.prototype.slice.call(arguments);//获取参数数组
const target = args.shift();//第一个参数为要改变的this值,在上面的例子中即为b
return function(){
return that.apply(target,args);
}
}

一个简易版的myBind实现了。