call和apply立即执行函数并改变this指向,区别在于参数传递方式;bind返回绑定this的新函数,不立即执行。

在JavaScript中,call、apply 和 bind 都是用来改变函数执行时的上下文,也就是 this 的指向。它们都属于函数的方法,定义在 Function.prototype 上,但使用方式和场景有所不同。
1. call:立即调用函数并指定 this 和参数
call 方法会立即执行函数,并将第一个参数作为函数体内 this 的值,后续参数依次传给函数。
语法:func.call(thisArg, arg1, arg2, ...)
适用场景:
- 借用其他对象的方法
- 函数式编程中快速改变上下文并执行
示例:
立即学习“Java免费学习笔记(深入)”;
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!');
// 输出:Hello, Alice!
2. apply:立即调用函数,参数以数组形式传入
apply 和 call 的作用完全一样,区别只在于传参方式:apply 接收一个参数数组。
语法:func.apply(thisArg, [argsArray])
适用场景:
- 参数数量不确定或已存在于数组中
- 求一组数的最大值、最小值(如 Math.max.apply(null, arr))
示例:
立即学习“Java免费学习笔记(深入)”;
const numbers = [5, 6, 2, 8]; const max = Math.max.apply(null, numbers); console.log(max); // 8
注意:ES6 中可以用扩展运算符替代 apply:
Math.max(...numbers);
3. bind:返回新函数,不立即执行
bind 不会立即调用函数,而是返回一个新函数,这个新函数的 this 被永久绑定到指定对象,后续可传参调用。
语法:func.bind(thisArg, arg1, arg2, ...)
适用场景:
- 事件处理中保持 this 指向原对象
- 函数柯里化(预设部分参数)
- setTimeout 或回调函数中维持上下文
示例:
立即学习“Java免费学习笔记(深入)”;
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.
核心区别总结
调用时机:
- call / apply:立即执行
- bind:返回绑定后的新函数,需手动调用
参数传递:
- call:逐个传参
- apply:传数组
- bind:支持预设参数(柯里化)
this 绑定:
- call / apply:临时改变一次 this
- bind:永久绑定 this,无法再被修改
基本上就这些。掌握这三个方法的关键是理解“何时执行”和“如何传参”。在实际开发中,bind 常用于保持上下文,call/apply 更适合一次性借用方法或处理数组参数。











