apply()
是 JavaScript 函数对象的一个方法,它的作用是调用一个函数,并且改变它的 this
指向,同时以数组形式传递参数。
func.apply(thisArg, [argsArray])
func
:要调用的函数。 thisArg
:执行 func
时绑定的 this
值(可以是 null
或 undefined
,此时 this
指向全局对象)。 [argsArray]
:一个数组或类数组对象,作为 func
的参数列表。 this
指向function greet(name) {
console.log(this.message + ', ' + name);
}
const obj = { message: 'Hello' };
greet.apply(obj, ['Tom']); // 输出:Hello, Tom
this
指向 obj
,所以 greet
里的 this.message
变成 obj.message
。
apply()
让 Math.max
计算数组的最大值const numbers = [3, 5, 9, 1, 6];
console.log(Math.max.apply(null, numbers)); // 9
等价于:
console.log(Math.max(...numbers)); // 9 (ES6 扩展运算符)
apply()
借用 Array.prototype.slice
function convertToArray() {
return Array.prototype.slice.apply(arguments);
}
console.log(convertToArray(1, 2, 3)); // [1, 2, 3]
🔹 arguments
是类数组对象,不能直接用 slice()
,但 apply()
让它变成真正的数组。
apply()
实现继承function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.apply(this, [name]); // 借用 Parent 的构造函数
this.age = age;
}
const child = new Child('Tom', 5);
console.log(child.name, child.age); // Tom 5
apply()
让 Child
继承 Parent
的属性。
apply()
vs call()
方法 | 作用 | 参数格式 |
---|---|---|
apply() |
改变 this 并调用函数 |
func.apply(thisArg, [argsArray]) |
call() |
改变 this 并调用函数 |
func.call(thisArg, arg1, arg2, ...) |
示例
function add(a, b) {
return a + b;
}
console.log(add.apply(null, [2, 3])); // 5
console.log(add.call(null, 2, 3)); // 5
apply()
用数组传参,call()
直接传入多个参数。
apply()
vs bind()
方法 | 作用 | 是否立即执行 |
---|---|---|
apply() |
绑定 this 并调用函数 |
立即执行 |
bind() |
绑定 this 并返回新函数 |
不立即执行 |
示例
function greet(name) {
console.log(this.message + ', ' + name);
}
const obj = { message: 'Hello' };
const boundFunc = greet.bind(obj);
boundFunc('Tom'); // Hello, Tom
greet.apply(obj, ['Tom']); // 立即执行:Hello, Tom
apply()
主要作用:
this
指向,使函数在指定对象上执行。Array.prototype.slice.apply(arguments)
把类数组转换成数组。apply()
让子类继承父类的属性。Math.max()
处理数组最大值 Math.max.apply(null, arr)
。核心区别
apply(this, [argsArray])
→ 数组传参,立即执行call(this, arg1, arg2, ...)
→ 逐个传参,立即执行bind(this, arg1, arg2, ...)
→ 返回新函数,不立即执行