call, apply, bind 区别

#call, apply, bind 区别及模拟实现call apply bind

      三者都可以用来改变this的指向,但是在用法上略有不同

 首先说一下call和apply的区别

  call和apply都是第一个参数是this的指向  ,只是传参的方式不同

  call是 第二个以及第三依次类推都是当前函数的参数,每个参数用逗号相隔开

  而apply则是将所有的参数以数组的形式来传递的

 call(window,参数1,参数1,参数3)

call和apply与bind的区别

call和apply相当于立即执行函数,使用时直接调用,而bind则类似于函数,使用时需要加()调用

同时bind传参方式与call相同,参数都是一个一个传递的

模拟实现call  

扫描二维码关注公众号,回复: 3965457 查看本文章

代码

Function.prototype.myCall = function (context) {
  var context = context || window
  // 给 context 添加一个属性
  // getValue.call(a, 'yck', '24') => a.fn = getValue
  context.fn = this
  // 将 context 后面的参数取出来
  var args = [...arguments].slice(1)
  // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
  var result = context.fn(...args)
  // 删除 fn
  delete context.fn
  return result
}

模拟实现apply   方式与call相似只是传参方式不同

 代码

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this

  var result
  // 需要判断是否存储第二个参数
  // 如果存在,就将第二个参数展开
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }

  delete context.fn
  return result
}

模拟实现bind

代码

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var args = [...arguments].slice(1)
  // 返回一个函数
  return function F() {
    // 因为返回了一个函数,我们可以 new F(),所以需要判断
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}

猜你喜欢

转载自www.cnblogs.com/katydids/p/9920472.html