区别
- call:
- 语法:
func.call(thisArg, arg1, arg2, ...)
。
- 特点:第一个参数是要绑定给函数内部
this
的对象,后面可以接收一系列参数,这些参数会依次作为函数的参数传入。
- apply:
- 语法:
func.apply(thisArg, [arg1, arg2, ...])
。
- 特点:第一个参数同样是要绑定给函数内部
this
的对象,但第二个参数是一个数组(或类数组对象),数组中的元素会依次作为函数的参数传入。
- bind:
- 语法:
func.bind(thisArg, arg1, arg2, ...)
。
- 特点:返回一个新的函数,这个新函数内部的
this
被永久绑定到bind
方法的第一个参数,后续调用新函数时传入的参数会追加在bind
方法中传入的参数之后。
示例
- call示例:
function greet() {
console.log(`Hello, ${this.name}!`);
}
const person = { name: 'John' };
greet.call(person);
- apply示例:
function sum(a, b) {
return a + b;
}
const numbers = [3, 5];
const result = sum.apply(null, numbers);
console.log(result);
- bind示例:
function sayHello() {
console.log(`Hello, ${this.name}!`);
}
const user = { name: 'Jane' };
const boundSayHello = sayHello.bind(user);
boundSayHello();