手写bind 以及 polyfill版本

137 阅读1分钟
  • Polyfill版本
var slice = Array.prototype.slice;
function bind(asThis) {
  // this 就是函数
  var args = slice.call(arguments, 1);
  var caller = this;
  if (typeof caller !== "function") {
    throw new Error("bind 必须调用在函数身上");
  }
  function resultFn() {
    var args2 = slice.call(arguments, 0);
    return caller.apply(
      resultFn.prototype.isPrototypeOf(this) ? this : asThis,
      args.concat(args2)
    );
  }
  resultFn.prototype = caller.prototype;
  return resultFn;
}
  • 全新版本
function _bind(asThis, ...args) {
  // this 就是函数
  const caller = this;
  function resultFn(...args2) {
    // resultFn.prototype.isPrototypeOf(this);
    return caller.call(this instanceof resultFn ? this : asThis, ...args, ...args2);
  }
  resultFn.prototype = caller.prototype;
  return resultFn;
}