js apply实现
apply 方法的基本概念
apply 是 JavaScript 中函数对象的一个方法,用于调用函数并允许指定函数的 this 值和参数数组。它的主要作用是在特定的上下文中调用函数,并传递参数列表(以数组或类数组形式)。
apply 的语法
function.apply(thisArg, [argsArray])
thisArg:可选参数,指定函数执行时的this值。如果为null或undefined,this会指向全局对象(非严格模式下)。argsArray:可选参数,是一个数组或类数组对象,包含传递给函数的参数。如果为null或undefined,表示不传递参数。
apply 的常见用途
改变函数的 this 指向
const obj = {
name: "Alice",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
const anotherObj = { name: "Bob" };
obj.greet.apply(anotherObj); // 输出: Hello, Bob
调用函数并传递参数数组

function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum.apply(null, numbers); // 输出: 6
借用其他对象的方法
const arrayLike = { 0: "a", 1: "b", length: 2 };
const realArray = Array.prototype.slice.apply(arrayLike);
console.log(realArray); // 输出: ["a", "b"]
apply 与 call 的区别
apply 和 call 功能类似,区别在于参数传递方式:

apply接受参数数组。call接受参数列表。
// 使用 call
sum.call(null, 1, 2, 3);
// 使用 apply
sum.apply(null, [1, 2, 3]);
手动实现 apply
以下是一个简单的 apply 实现(Polyfill):
Function.prototype.myApply = function(thisArg, argsArray) {
// 如果 thisArg 为 null 或 undefined,默认指向全局对象
thisArg = thisArg || window;
// 确保 argsArray 是一个数组或类数组
argsArray = argsArray || [];
// 为 thisArg 创建一个临时唯一属性,避免属性冲突
const fnSymbol = Symbol();
thisArg[fnSymbol] = this;
// 调用函数并传递参数
const result = thisArg[fnSymbol](...argsArray);
// 删除临时属性
delete thisArg[fnSymbol];
return result;
};
// 测试
function greet(message) {
console.log(`${message}, ${this.name}`);
}
const person = { name: "Charlie" };
greet.myApply(person, ["Hi"]); // 输出: Hi, Charlie
注意事项
- 在严格模式下,
thisArg为null或undefined时,this不会指向全局对象。 argsArray如果不是数组或类数组对象,会抛出异常。apply的性能略低于直接调用函数,但在需要动态指定this或参数时非常有用。
实际应用示例
合并数组
const arr1 = [1, 2];
const arr2 = [3, 4];
arr1.push.apply(arr1, arr2);
console.log(arr1); // 输出: [1, 2, 3, 4]
查找数组最大值
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max); // 输出: 7






