call 和 bind 都是用于改变 JavaScript 中函数的 this 对象的上下文,但它们的实现和使用方式是不同的。
call 方法直接调用一个函数,并且把新的 this 对象的值作为它的第一个参数传递给函数,其余参数依次传递:
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
const object = { name: 'aaaa' };
greet.call(object, 'Hello', '!!!'); // "Hello aaaa!!!"
bind 方法创建一个新函数,并且在调用该函数时将其 this 对象绑定到指定值,该函数可以用于以后调用:
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
constobject = { name: 'aaaa' };
const boundGreet = greet.bind(object);
boundGreet('Hello', '!!!'); // "Hello aaaaa!!!"
总的来说,如果你想立即调用一个函数并改变它的 this 对象,那么你可以使用 call;如果你想创建一个新函数并在以后调用它,并且在调用时始终改变其 this 对象,那么你可以使用 bind。