JS 中call、apply 和 bind使用方法和场景
call 方法
- 核心特性
- 立即执行函数,并显式指定 this 值和逐个传递参数。
- 语法:func.call(thisArg, arg1, arg2, …)
- 使用场景
借用其他对象的方法
const person = { name: "Alice" };
function greet(greeting) {console.log(`${greeting}, ${this.name}!`);
}
greet.call(person, "Hello"); // 输出 "Hello, Alice!"
处理类数组对象
function sum() {const args = Array.prototype.slice.call(arguments); // 转为真实数组return args.reduce((acc, val) => acc + val, 0);
}
sum(1, 2, 3); // 输出 6
. 链式调用构造函数(继承场景)
function Parent(name) {this.name = name;
}
function Child(name, age) {Parent.call(this, name); // 调用父类构造函数this.age = age;
}
const child = new Child("Bob", 10);
apply 方法
- 核心特性
- 立即执行函数,并显式指定 this 值和以数组形式传递参数。
- 语法:func.apply(thisArg, [argsArray])
- 使用场景
- 动态参数传递
const numbers = [5, 1, 9, 3];
const max = Math.max.apply(null, numbers); // ES5 中求数组最大值
console.log(max); // 输出 9
// ES6+ 替代方案:Math.max(...numbers)
- 合并数组
const arr1 = [1, 2];
const arr2 = [3, 4];
arr1.push.apply(arr1, arr2); // 合并数组(等同于 arr1.push(...arr2))
console.log(arr1); // 输出 [1, 2, 3, 4]
- 函数参数转发
function wrapper() {const args = Array.prototype.slice.call(arguments);// 将参数数组转发给其他函数doSomething.apply(this, args);
}
bind 方法
- 核心特性
- 不立即执行函数,而是返回一个绑定 this 的新函数,参数可预先固定。
- 语法:func.bind(thisArg, arg1, arg2, …)
- 使用场景
- 延迟执行固定this
const user = { name: "Charlie" };
function showName() {console.log(this.name);
}
const boundShowName = showName.bind(user);
setTimeout(boundShowName, 1000); // 1秒后输出 "Charlie"
- 事件监听器绑定上下文
class Button {constructor() {this.text = "Click me";this.element = document.createElement("button");// 绑定 this,确保回调中的 this 指向实例this.element.addEventListener("click", this.handleClick.bind(this));}handleClick() {console.log(this.text); // 输出 "Click me"}
}
- 函数柯里化(部分参数固定)
function multiply(a, b) {return a * b;
}
const double = multiply.bind(null, 2); // 固定第一个参数为 2
console.log(double(5)); // 输出 10 (即 2 * 5)
三者对比
方法 | 执行时机 | 参数形式 | 典型场景 | ES6+ 替代方案 |
---|---|---|---|---|
call | 立即执行 | 参数列表 | 明确参数、借用方法 | 扩展运算符 … |
apply | 立即执行 | 数组 | 动态参数、数组合并 | 扩展运算符 … |
导bind | 返回函数 | 参数列表(可部分) | 延迟执行、事件绑定、柯里化 | 箭头函数(固定 this) |