推荐答案
// www.javascriptcn.com code example
function myApply(fn, context, args) {
// 如果 context 是 null 或 undefined,则默认为全局对象(浏览器中是 window)
context = context || window;
// 将 fn 作为 context 的一个属性
context.fn = fn;
// 调用函数,并传入参数
const result = context.fn(...args);
// 删除 context 上的 fn 属性
delete context.fn;
// 返回函数执行结果
return result;
}本题详细解读
1. 函数功能
myApply 函数模拟了 Function.prototype.apply 的行为。apply 方法允许你调用一个函数,并且可以指定 this 的值以及一个数组(或类数组对象)作为参数。
2. 参数说明
fn: 需要调用的函数。context: 函数执行时的this值。如果为null或undefined,则默认为全局对象(在浏览器中是window)。args: 一个数组或类数组对象,包含传递给函数的参数。
3. 实现步骤
- 处理
context: 如果context是null或undefined,则将其设置为全局对象(在浏览器中是window)。 - 将
fn绑定到context: 将fn作为context的一个属性,这样在调用时this就会指向context。 - 调用函数: 使用
context.fn(...args)调用函数,并传入参数。 - 清理: 删除
context上的fn属性,以避免污染context对象。 - 返回结果: 返回函数执行的结果。
4. 示例
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const person = { name: 'Alice' };
console.log(myApply(greet, person, ['Hello', '!'])); // 输出: "Hello, Alice!"在这个示例中,greet 函数通过 myApply 调用,this 被绑定到 person 对象,并且传递了 ['Hello', '!'] 作为参数。