Call、Apply、Bind手写代码

108 阅读1分钟

写自己的手写代码

call

Function.prototype.myCall = function (context) {
  // 必须是函数才能绑定
  if (typeof this !== 'function') return
  var args = [...arguments].slice(1)
  var context = context || window
  var fn = Symbol('')
  context[fn] = this
  var result = context[fn](...args)
  delete context[fn]
  return result
}

apply

Function.prototype.myApply = function (context) {
  if (typeof this !== 'function') return
  var args = arguments[1]
  var fn = Symbol('fn')
  var result = null
  var context = context || window
  context[fn] = this
  if (!args) {
    result = context[fn]();
  } else {
    result = context[fn](...args);
  }
  delete context[fn]
  return result
}

bind

Function.prototype.myBind = function (context) {
  var args = [...arguments].slice(1)
  var fn = this
  return function f() {
    args = [...args, ...arguments]
    if (this instanceof f) {
      return new fn(...args)
    } else {
      return fn.apply(context, args)
    }
  }
}