实现一个bind函数

189 阅读1分钟

谢谢开龙推荐的书,跟颓废小半年的自己说拜拜,我又活过来了!也许还可以继续热爱嘻嘻

Function.prototype.bind = Function.prototype.bind || function(context) {
   const self = this;
   // 绑定bind时传的参数, 第一个为绑定的对象
   const args = [].slice.call(arguments, 1);
   const defaultContext = [].shift.call(arguments);
   return function bound(){
      // 调用时传参
      const callArgs = [].slice.call(arguments);
      // 最终参数列表
      const finallyArgs = args.concat(callArgs);
      // 绑定的对象
      const finallContext = context || defaultContext;
      return self.apply(context, finallyArgs)
    }
}

说明:
1.arguments是一个类数组对象,也就不是数组,所以没有slice、shift等方法,故借用[].来借用对应的方法([].slice 等价于 Array.prototype.slice2.slice: 从已有的数组中返回选定的元素。 arrayObject.slice(start,end) 包括start不包括end
3.shift: 把数组的第一个元素从其中删除,并返回第一个元素的值