apply, call, 和 bind 都是用来改变函数内部的 this 值的方法。
call
- call 方法用于调用一个函数,并将该函数的 this 值设置为提供的参数。
- call 接受的第一个参数是指定的 this 值,之后的参数列表会被依次传递给函数作为实参。
function greet(greeting, name) {
console.log(greeting + ', ' + this.title + ' ' + name);
}
var obj = { title: 'Mr' };
greet.call(obj, 'Hello', 'John'); // 输出 "Hello, Mr John"
apply
- apply 类似于 call,但它接受两个参数:第一个参数是指定的 this 值,第二个参数是一个数组(或类数组对象),其元素会被作为单独的参数传递给函数。
function greet(greeting, name) {
console.log(greeting + ', ' + this.title + ' ' + name);
}
var obj = { title: 'Mr' };
greet.apply(obj, ['Hello', 'John']); // 输出 "Hello, Mr John"
bind
- bind 创建一个新的函数,当这个新函数被调用时,它的 this 值会被设置为 bind 的第一个参数所指定的对象。
- bind 还可以接受额外的参数,这些参数会在新创建的函数被调用时作为初始参数传递。
function greet(greeting, name) {
console.log(greeting + ', ' + this.title + ' ' + name);
}
var obj = { title: 'Mr' };
var boundGreet = greet.bind(obj, 'Hello');
boundGreet('John'); // 输出 "Hello, Mr John"
总结
- call 和 apply 都立即执行函数,并且都可以改变函数内部的 this 指向。
- bind 创建一个新的函数,并改变了新函数内部的 this 指向,但并不会立即执行原函数。
- call 和 bind 使用逗号分隔的参数列表来传递参数,而 apply 使用数组来传递参数列表。
注意:三者第一个参数都是 this 要指向的对象,如果没有这个参数或参数为 undefined 或 null,则默认指向全局 window