apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
以上是 MDN 中对于 call, apply, bind 三者的介绍。
简单来说,通过 call,apply,bind 可以改变 eat 中 this 的指向。
const dog = {
name: 'dog',
age: 2,
eat: function() {
console.log(`A ${this.age}-year-old ${this.name} is eating.`);
}
};
// eat 函数中的 this 此时指向 dog
console.log(dog.eat()); // A 2-year-old dog is eating.
call
const cat = {
name: 'cat',
age: 3,
};
// eat 函数中的 this 指向了 cat。
console.log(dog.eat.call(cat)); // A 3-year-old cat is eating.
函数签名:function.call(thisArg, arg1, arg2, ...)
thisArg 可选的。在 function 函数运行时使用的 this 值。arg1, arg2, ...指定的参数列表。
apply
该方法的语法和作用与 call() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。
function eat(...food){
console.log(`${this.name} eat ${food.join(', ')}.`);
}
// 二者等价
eat.call({name:'Dog'},'apple','bones'); // Dog eat apple, bones.
eat.apply({name:'Dog'},['apple','bones']); // Dog eat apple, bones.
函数签名:function.apply(thisArg, [argsArray])
bind
正如我们看到的字面意思(绑定)一样,bind 是用来绑定 this 指向的,它返回一个被绑定this后的新函数。请看如下例子:
const dog = {
name: 'dog',
age: 2,
eat: function() {
console.log(`A ${this.age}-year-old ${this.name} is eating.`);
}
};
dog.eat(); // A 2-year-old dog is eating.
const cat = {
name: 'cat',
age: 3,
};
dog.eat = dog.eat.bind(cat);
//此时this已经指向了cat
dog.eat(); // A 3-year-old cat is eating.
函数签名:function.bind(thisArg, arg1, arg2, ...)