手写系列 - call、apply、bind

68 阅读1分钟

Function.prototype.call = function (obj, ...args) {
  obj = obj || window
  obj.fn = this
  let res = obj.fn(...args)
  delete obj.fn;
  return res;
}




Function.prototype.apply = function (obj, args) {
  obj = obj || window
  obj.fn = this
  let res = null
  if (!args) {
    res = obj.fn();
  } else {
    res = obj.fn(...args)
  }
  delete obj.Fn
  return res;
}


//  bind 的不同之处是 bind 函数返回的是一个函数,而不执行调用者函数。
//  第二是 bind 函数具有柯里化特性的即:参数可以在绑定 this 时传入一部分,在调用时再传入一部分。


Function.prototype.bind = function (obj) {
  let args = [...arguments].slice(1)
  let fn = this;

  return function Fn() {
    return fn.apply(
      this instanceof Fn ? this : obj
      args.concat(...arguments)
    )
  }