js apply 实现
apply 方法的基本概念
apply 是 JavaScript 中函数对象的一个方法,用于调用函数并指定函数内部的 this 值和参数列表。它的语法如下:
function.apply(thisArg, [argsArray])
thisArg:函数运行时使用的this值。argsArray:一个数组或类数组对象,包含传递给函数的参数。
使用 apply 调用函数
apply 的主要用途之一是显式设置函数内部的 this 值。例如:
const person = {
name: 'Alice',
greet: function(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
};
const anotherPerson = { name: 'Bob' };
person.greet.apply(anotherPerson, ['Hello']); // 输出: Hello, Bob!
这里,greet 方法原本属于 person 对象,但通过 apply 将其 this 值设置为 anotherPerson,从而实现了方法的借用。
apply 与参数传递
apply 的第二个参数是一个数组或类数组对象,其中的元素会作为单独的参数传递给函数。例如:
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum.apply(null, numbers); // 输出: 6
由于不需要改变 this 值,这里传入 null 作为第一个参数。
apply 实现继承或方法借用
apply 可以用于实现类似继承的功能,或者在对象之间共享方法。例如:
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.apply(this, [name, price]);
this.category = 'food';
}
const cheese = new Food('Cheese', 5);
console.log(cheese.name); // 输出: Cheese
通过 apply,Food 构造函数调用了 Product 构造函数,从而继承了 Product 的属性。
apply 与数组操作
apply 常用于处理数组操作,尤其是需要将数组展开为单独参数的场景。例如:
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers); // 输出: 7
这里,apply 将数组 numbers 展开为 Math.max 的单独参数。
apply 的替代方案
在现代 JavaScript 中,apply 的许多用途可以被展开运算符(...)替代。例如:
const numbers = [1, 2, 3];
const result = sum(...numbers); // 输出: 6
展开运算符更简洁,但在某些旧代码或特定场景中,apply 仍然有用。

apply 的注意事项
- 如果
thisArg为null或undefined,函数内部的this会指向全局对象(非严格模式下)。 argsArray可以是类数组对象(如arguments),不一定是严格意义上的数组。- 在严格模式下,
thisArg不会被强制转换为对象,且未指定时this为undefined。






