bind,call,apply手写面试题

150 阅读1分钟

bind实现

注意点:

  • bind()返回的是函数本身, 利用apply改变原函数内部this的指向
Function.prototype.myBind = function(context) {
  context = context || window
  let originFn = this;
  return function() {
    let args = Array.prototype.slice.call(arguments, 0);
    originFn.apply(context, args);
  }
}

call实现

注意点:

  • 若绑定的context上下文为null,则默认给window
  • 收集从第二个参数开始的所有参数
  • 在绑定的context上下文上定义参数指向当前函数,并在执行完后删除该属性
Function.prototype.mycall = function(context) {
  context = context || window
  let args = []
  for(let i = 1; i < arguments.length; i++) {
    args.push(arguments[i])
  }
  context.fn = this
  let result = context.fn(...args)
  delete context.fn
  return result
}

apply实现

注意点:

  • 类似上面call的实现,不同点在于apply第二个参数是为一个数组,传递给函数的时候会利用rest展开数组
Function.prototype.myapply = function(context) {
  context = context || window
  let args = arguments[1]
  context.fn = this
  let result = context.fn(...args)
  delete context.fn
  return result
}