js实现call
实现 call 方法
在 JavaScript 中,call 方法用于调用一个函数,并允许指定函数执行时的 this 值和参数列表。以下是手动实现 call 的方法:
Function.prototype.myCall = function(context, ...args) {
context = context || window;
const fn = Symbol('fn');
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
};
代码解析
-
绑定上下文
context参数表示函数执行时的this值。如果未传入context,则默认为window(浏览器环境)或global(Node.js 环境)。 -
临时属性存储函数
使用Symbol创建一个唯一的属性名,避免与context对象的现有属性冲突。将当前函数(this)赋值给context的这个临时属性。 -
执行函数并获取结果
通过context[fn](...args)调用函数,并传入参数列表。此时函数的this指向context。 -
清理临时属性
删除临时添加的属性,避免污染context对象。 -
返回结果
返回函数执行的结果。
使用示例
function greet(message) {
console.log(`${message}, ${this.name}`);
}
const person = { name: 'Alice' };
greet.myCall(person, 'Hello'); // 输出: Hello, Alice
注意事项
- 如果传入的
context是原始值(如数字、字符串等),call方法会自动将其转换为对象形式。 - 手动实现的
myCall方法与原生call行为一致,但未处理某些边界情况(如context为null或undefined时的严格模式行为)。
通过这种方式,可以深入理解 call 方法的底层实现逻辑。






