原声js实现call
实现原声 JavaScript 的 call 方法
call 方法是 JavaScript 中函数原型的一个方法,用于在特定的作用域中调用函数,并可以传递参数。以下是实现 call 方法的具体步骤:
基本思路
call 方法的核心在于改变函数的执行上下文(即 this 的指向),并将参数逐个传递给函数。可以通过将函数作为对象的属性来调用,从而实现 this 的绑定。

具体实现
在 Function.prototype 上添加自定义的 myCall 方法:

Function.prototype.myCall = function(context, ...args) {
// 如果 context 为 null 或 undefined,则默认指向全局对象(浏览器中为 window)
context = context || window;
// 将当前函数(即调用 myCall 的函数)作为 context 的一个属性
context.fn = this;
// 调用函数,并传递参数
const result = context.fn(...args);
// 删除临时添加的属性
delete context.fn;
// 返回函数执行结果
return result;
};
示例测试
测试自定义的 myCall 方法是否正常工作:
function greet(message) {
console.log(`${message}, ${this.name}`);
}
const person = {
name: 'Alice'
};
// 使用原生 call 方法
greet.call(person, 'Hello'); // 输出: Hello, Alice
// 使用自定义的 myCall 方法
greet.myCall(person, 'Hi'); // 输出: Hi, Alice
注意事项
- 如果
context是原始值(如数字、字符串、布尔值),需要将其转换为对象形式(如new Number()、new String())。 - 在严格模式下,如果
context为null或undefined,this会指向undefined,而非全局对象。
完整代码
以下是完整的实现代码,包括对原始值的处理:
Function.prototype.myCall = function(context, ...args) {
// 处理 context 为 null 或 undefined 的情况
context = context == null ? window : context;
// 处理原始值的情况
if (typeof context !== 'object') {
context = new Object(context);
}
// 将函数作为 context 的属性
context.fn = this;
// 调用函数并获取结果
const result = context.fn(...args);
// 删除临时属性
delete context.fn;
return result;
};
通过以上实现,可以模拟原生 call 方法的功能,实现函数调用时动态绑定 this 的效果。






