浅显易懂call,apply,bind的区别

104 阅读1分钟

call,apply,bind都是可以改变this的指向,那么它们三者之间的区别是什么,我们今天来看看。


先看这段代码:

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  },
  getName: function(a, b) {
    console.log(this.name, a+b)
  }
};

adventurer.getName(1, 2) // "Alice" 3

const user = {
  name: 'yebuyu'
}

adventurer.getName.call(user, 3, 4) // yebuyu" 7

adventurer.getName.apply(user, [3, 4]) // "yebuyu" 7

adventurer.getName.bind(user, 3, 4)() // "yebuyu" 7

adventurer.getName.bind(user)(3, 5) // "yebuyu" 8

adventurer.getName.bind(user, 3)(5) // "yebuyu" 8

  • call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象

  • call 从第二个参数开始为调用的函数参数,并且是以逗号隔开;apply的第二个参数为数组,数组元素为调用的函数参数;bind 的传参跟call一样;

  • call和apply是直接执行函数;但是bind 返回的是一个新的函数,你必须调用它才会被执行故加上()调用函数;

  • bind()函数有两个地方可以传参;可参考代码