call、apply、bind的区别

103 阅读2分钟

call(),apply(),bind()这三个函数存在的意义是改变函数执行时的上下文,换句话来说,这三个函数的意义就是改变函数运行时的this的指向

call和apply的区别

这两个函数的作用都是一样的,区别在于接受的参数不同

  • call()方法接受两个参数,第一个参数是this的指向,第二个参数是函数参数,要逐个地列出来,当第一个参数为null或者为undefined的时候,默认指向window。
  • apply也是接受两个参数,第一个参数为this指向,第二个参数以数组或者arguments对象的形式传入;同样地,当第一个参数为null、undefined的时候,默认指向window。

call

 const person = {
    name: 'jack',
    age: 18,
    introduce() {
        console.log(`Hi My name is ${this.name}. I'm ${this.age}`);
    }
}
const myFriend = {
  name: 'ross',
  age: '16'
}
console.log(person.introduce()) //Hi My name is jack. I'm 18
console.log(person.introduce.call(myFriend)) //Hi My name is ross. I'm 16

通过call,为introduce这个函数中的this指向了myFriend。
再来看一个红宝书里的call例子:

 function sum(num1,num2){
   return num1+num2;
 }
 function callSum(num1,num2){
  return sum.call(this,num1,num2)
 }
 console.log(callSum(10,10)) //20

举这个例子主要是为了突出call的传参方式。

apply

function displayHobbies(...hobbies) {
    console.log(`${this.name} likes ${hobbies.join(', ')}.`);
}
// 下面两个等价
displayHobbies.call({ name: 'Bob' }, 'swimming', 'basketball', 'anime'); // => // => Bob likes swimming, basketball, anime. 
displayHobbies.apply({ name: 'Bob' }, ['swimming', 'basketball', 'anime'])
。

综上,使用call还是apply,取决于怎么给调用的函数传参更方便,如果想直接传数组或者是arguments对象,用apply就好了,否则就使用call。

bind

bind方法创建一个新的函数,在bind()被调用时,这个新函数的this被指定为bind()的第一个参数,而其余参数将作为新函数的参数,供调用是使用。

 const person = {
    name: 'jack',
    age: 18,
}
function introduce(){
  console.log(`Hi My name is ${this.name}. I'm ${this.age}`);
}
const myFriend = {
  name: 'ross',
  age: '16'
}
person.introduce = introduce.bind(myFriend);
console.log(person.introduce())////Hi My name is ross. I'm 16
console.log(person.introduce.call(myFriend)) //Hi My name is ross. I'm 16

参考链接:
www.zhihu.com/search?type…
zhuanlan.zhihu.com/p/82340026
www.yuque.com/gangafengli…