call、band、aplay 之间的的区别

79 阅读1分钟

它们都是 JavaScript 中用于改变函数 this 指向的方法,主要区别如下:

执行时机

  • call 和 apply:会立即执行被调用的函数237。
  • bind:不会立即执行,而是返回一个新的函数,当这个新函数被调用时才会执行123。

传参方式

  • call:参数是逐个传递的,第一个参数是要绑定的 this 值,后面的参数依次是传递给函数的参数123。
  • apply:第二个参数是一个数组或类数组对象,数组中的元素作为参数传递给函数123。
  • bind:可以像 call 一样逐个传参,也可以先传入一部分参数,在返回的新函数被调用时再传入剩余参数4。

对原函数的影响

  • call 和 apply:只是临时改变函数的 this 指向,在函数执行完后,原函数的 this 指向不会被永久改变3。

  • bind:返回一个新的函数,新函数的 this 被永久绑定到传入 bind 的第一个参数上,原函数不受影响3。

以下是一个简单的示例来展示它们的区别:

javascript

const person = {
    name: 'John',
    sayHello: function(greeting) {
        console.log(`${greeting}, my name is ${this.name}`);
    }
};

const anotherPerson = {
    name: 'Jane'
};

// 使用call
person.sayHello.call(anotherPerson, 'Hi'); 

// 使用apply
person.sayHello.apply(anotherPerson, ['Hello']); 

// 使用bind
const boundFunction = person.sayHello.bind(anotherPerson, 'Hey');
boundFunction();