call和apply立即执行函数并改变this指向,区别在于参数传递方式;bind返回绑定this的新函数,不立即执行。
在JavaScript中,call、apply 和 bind 都是用来改变函数执行时的上下文,也就是 this 的指向。它们都属于函数的方法,定义在 Function.prototype 上,但使用方式和场景有所不同。
call 方法会立即执行函数,并将第一个参数作为函数体内 this 的值,后续参数依次传给函数。
语法:func.call(thisArg, arg1, arg2, ...)
适用场景:
程中快速改变上下文并执行示例:
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!');
// 输出:Hello, Alice!
apply 和 call 的作用完全一样,区别只在于传参方式:apply 接收一个参数数组。
语法:func.apply(thisArg, [argsArray])
适用场景:
示例:
const numbers = [5, 6, 2, 8]; const max = Math.max.apply(null, numbers); console.log(max); // 8
注意:ES6 中可以用扩展运算符替代 apply:
Math.max(...numbers);
bind 不会立即调用函数,而是返回一个新函数,这个新函数的 this 被永久绑定到指定对象,后续可传参调用。
语法:func.bind(thisArg, arg1, arg2, ...)
适用场景:
示例:
function introduce() {
console.log(`I am ${this.name}, ${this.age} years old.`);
}
const user = { name: 'Bob', age: 25 };
const boundIntro = introduce.bind(user);
setTimeout(boundIntro, 1000);
// 一秒后输出:I am Bob, 25 years old.
调用时机:
参数传递:
this 绑定:
基本上就这些。掌握这三个方法的关键是理解“何时执行”和“如何传参”。在实际开发中,bind 常用于保持上下文,call/apply 更适合一次性借用方法或处理数组参数。