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