fe_interview icon indicating copy to clipboard operation
fe_interview copied to clipboard

手写bind()

Open Cosen95 opened this issue 4 years ago • 1 comments

Cosen95 avatar Apr 07 '20 08:04 Cosen95

参考冴羽大佬实现:

Function.prototype.bind2 = function (context) {
  if (typeof this !== "function") {
    throw new Error(
      "Function.prototype.bind - what is trying to be bound is not callable"
    );
  }
  var self = this;
  // 获取bind2函数从第二个参数到最后一个参数
  var args = Array.prototype.slice.call(arguments, 1);

  var fNOP = function () {};
  var fbound = function () {
    // 这个时候的arguments是指bind返回的函数传入的参数
    var bindArgs = Array.prototype.slice.call(arguments);
    return self.apply(
      this instanceof fNOP ? this : context,
      args.concat(bindArgs)
    );
  };
  fNOP.prototype = this.prototype;
  fbound.prototype = new fNOP();
  return fbound;
};

Cosen95 avatar Sep 10 '20 09:09 Cosen95