1. 共同点
- 作用:都可以改变函数调用时的 this 指向。
- 用法:都在函数对象上调用,如
fn.bind(...) / fn.call(...) / fn.apply(...)。
2. 区别
① call
- 语法:
fn.call(thisArg, arg1, arg2, ...)
- 作用:立即调用函数,
this 指向 thisArg。
- 参数传递:逐个传。
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello', '!');
// 输出: Hello, Alice!
② apply
- 语法:
fn.apply(thisArg, [argsArray])
- 作用:立即调用函数,
this 指向 thisArg。
- 参数传递:以数组形式传递(适合参数数量不确定时)。
greet.apply(person, ['Hi', '...']);
// 输出: Hi, Alice...
③ bind
- 语法:
const newFn = fn.bind(thisArg, arg1, arg2, ...)
- 作用:不会立即调用,返回一个新函数,this 永久绑定为
thisArg。
- 参数传递:可以在 bind 时预置一部分参数(柯里化)。
const greetAlice = greet.bind(person, 'Hey');
greetAlice('?');
// 输出: Hey, Alice?
3. 直观对比表
| 方法 | 是否立即调用 | 参数形式 | 返回值 |
|---|
| call | ✅ 立即调用 | 单个参数列表 | 函数执行结果 |
| apply | ✅ 立即调用 | 参数数组 | 函数执行结果 |
| bind | ❌ 不调用 | 单个参数列表(可预置) | 新函数(this 被绑定) |
4. 使用场景
- call:快速调用并改变 this。
Array.prototype.forEach.call(document.querySelectorAll('div'), el => console.log(el));
- apply:需要数组展开的场景。
Math.max.apply(null, [1, 5, 3]); // 5
- bind:需要延迟调用 / 绑定事件回调时。
button.onclick = handler.bind(obj);
文章评论