美文网首页
call, apply, bind 区别

call, apply, bind 区别

作者: 小雨雪smile | 来源:发表于2019-08-13 14:55 被阅读0次

首先说下前两者的区别。

callapply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同。

除了第一个参数外,call 可以接收一个参数列表,apply 只接受一个参数数组。

let a = {
    value: 1
}
function getValue(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value)
}
getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])

模拟实现 call 和 apply

可以从以下几点来考虑如何实现

  • 不传入第一个参数,那么默认为 window
  • 改变了 this 指向,让新的对象可以执行该函数。那么思路是否可以变成给新的对象添加一个函数,然后在执行完以后删除?
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
}

以上就是 call 的思路,apply 的实现也类似

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 和其他两个方法作用也是一致的,只是该方法会返回一个函数。并且我们可以通过 bind 实现柯里化。

同样的,也来模拟实现下 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))
  }
}

相关文章

  • 理解JS中的 call, apply, bind方法

    call, apply, bind 方法的目的和区别 我们常说,call(), apply(),bind()方法的...

  • this_原型链_继承

    this相关问题 apply、call 、bind的作用以及区别 call、apply和bind方法的用法以及区别...

  • this&原型链&继承

    this 1. apply、call 、bind有什么作用,什么区别? apply、call 、bind 都是用来...

  • this_原型链_继承

    this 相关 1. apply、call 、bind有什么作用,什么区别 apply、call、bind可以改变...

  • 关于 this_原型链_继承 相关问题总结

    关于this 1- apply、call 、bind的作用和区别 apply、call 、bind都有改变thi...

  • this_原型链_继承

    问题1: apply、call 、bind有什么作用,什么区别? apply和call call apply,调用...

  • this 原型链 继承

    this 相关问题 1.apply、call 、bind有什么作用,什么区别 apply、call 、bind这三...

  • call(),apply()和bind()

    call、apply和bind函数存在的区别:bind返回对应函数, 便于稍后调用; apply, call则是立...

  • this 相关问题

    问题1: apply、call 、bind有什么作用,什么区别 apply call bind 问题2: 以下代码...

  • js继承

    问题1: apply、call 、bind有什么作用,什么区别 apply/call/bind 问题2: 以下代码...

网友评论

      本文标题:call, apply, bind 区别

      本文链接:https://www.haomeiwen.com/subject/sfxbjctx.html