Function.prototype.bind实现

29 阅读1分钟

目标

实现函数Function.prototype.mybind,效果等同于Function.prototype.bind

bind接受参数为:(thisArg, ...args)

实现

利用apply函数实现:

Function.prototype.mybind = function(thisArg, ...args) {
  const fn = this;
  
  function bound(...innerArgs) {
    const context = (this instanceof bound) ? this : thisArg;
  
    return fn.apply(context, [...args, ...innerArgs]);
  }
  
  if (fn.prototype){
    bound.prototype = Object.create(fn.prototype);
    bound.prototype.constructor = bound;
  }

  return bound;
}

这里有一个细节,当得到了bound = fn.bind(obj1)后,再次调用bound2 = bound.bind(obj2),会忽略这个bind调用,bound2bound运行时的this都指向obj1。该行为手写bind与原始bind表现一致。

问题

bound.prototype应该为undefined