js实现apply函数

实现 apply 函数
JavaScript 的 apply 方法是函数原型上的一个方法,用于在特定的作用域中调用函数,并允许以数组形式传递参数。以下是手动实现 apply 的方法:
核心思路
- 将函数设置为目标对象的属性。
- 以数组形式传递参数并调用函数。
- 删除临时添加的属性。
- 返回函数执行结果。
代码实现
Function.prototype.myApply = function(context, argsArray) {
// 如果 context 为 null 或 undefined,默认指向全局对象(浏览器中为 window)
context = context || window;
// 确保 argsArray 是数组或类数组对象
argsArray = argsArray || [];
// 为 context 创建一个唯一属性,避免属性名冲突
const fnKey = Symbol('tempFn');
context[fnKey] = this;
// 调用函数并传递参数
const result = context[fnKey](...argsArray);
// 删除临时属性
delete context[fnKey];
return result;
};
使用示例
function greet(message1, message2) {
console.log(`${message1}, ${this.name}! ${message2}`);
}
const person = { name: 'Alice' };
// 原生 apply
greet.apply(person, ['Hello', 'How are you?']); // 输出: Hello, Alice! How are you?
// 自定义 myApply
greet.myApply(person, ['Hi', 'Nice to meet you']); // 输出: Hi, Alice! Nice to meet you
边界情况处理
- 如果
context是原始值(如数字、字符串),需要转换为对象。 - 如果
argsArray不是数组或类数组对象,需要抛出错误或处理为空数组。 - 使用
Symbol避免属性名冲突,确保不会覆盖目标对象的原有属性。
优化版本
Function.prototype.myApply = function(context, argsArray) {
if (typeof this !== 'function') {
throw new TypeError('myApply must be called on a function');
}
context = context == null ? window : Object(context);
argsArray = Array.isArray(argsArray) ? argsArray : [];
const fnKey = Symbol();
context[fnKey] = this;
const result = context[fnKey](...argsArray);
delete context[fnKey];
return result;
};
通过以上实现,可以模拟原生 apply 方法的功能,包括作用域绑定和参数传递。







