1. 使用方式区别
call
:func.call(thisArg, arg1, arg2, ...)
,thisArg
为函数执行时this
指向的对象,后续参数arg1, arg2, ...
为传递给函数的参数,按顺序依次列出。
apply
:func.apply(thisArg, [arg1, arg2, ...])
,thisArg
同样是函数执行时this
指向的对象,但第二个参数是一个数组,该数组包含要传递给函数的所有参数。
bind
:func.bind(thisArg, arg1, arg2, ...)
,thisArg
是函数执行时this
指向的对象,后续参数arg1, arg2, ...
为传递给函数的参数。bind
方法返回一个新函数,不会立即执行原函数。
2. 功能特性区别
call
和 apply
:这两个方法都会立即执行调用它们的函数,并将函数中的this
指向thisArg
。它们的主要区别仅在于传递参数的形式。
bind
:bind
方法返回一个新的函数,这个新函数的this
被绑定到thisArg
,并且可以预先传入部分参数。新函数在调用时,this
始终指向bind
方法中指定的thisArg
,不会被其他方式改变。
3. 改变this
指向示例
// 定义一个对象
const person = {
name: 'John',
age: 30,
sayHello: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
};
// 定义另一个对象
const anotherPerson = {
name: 'Jane',
age: 25
};
// 使用 call 改变 this 指向
person.sayHello.call(anotherPerson);
// 输出: Hello, my name is Jane and I'm 25 years old.
// 使用 apply 改变 this 指向
person.sayHello.apply(anotherPerson);
// 输出: Hello, my name is Jane and I'm 25 years old.
// 使用 bind 改变 this 指向
const newFunction = person.sayHello.bind(anotherPerson);
newFunction();
// 输出: Hello, my name is Jane and I'm 25 years old.
// 带参数函数示例
const add = function(a, b) {
return this.value + a + b;
};
const obj = { value: 1 };
// call 传递参数
const resultCall = add.call(obj, 2, 3);
console.log(resultCall);
// 输出: 6
// apply 传递参数
const resultApply = add.apply(obj, [2, 3]);
console.log(resultApply);
// 输出: 6
// bind 传递参数
const newAdd = add.bind(obj, 2);
const resultBind = newAdd(3);
console.log(resultBind);
// 输出: 6