call 实现 js
使用 call 方法实现 JavaScript 函数调用
call 是 JavaScript 中函数对象的一个方法,用于显式指定函数执行时的 this 值,并传递参数列表。其语法为:

function.call(thisArg, arg1, arg2, ...)
基本用法示例
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.title}.`);
}
const person = { title: 'Developer' };
greet.call(person, 'Alice'); // 输出: Hello, Alice! I'm Developer.
通过 call 将 this 绑定到 person 对象,并传递参数 'Alice'。
实现类似 call 的功能
若要手动实现类似 call 的功能,可通过以下方式模拟:
Function.prototype.myCall = function(thisArg, ...args) {
// 确保 thisArg 不为 null 或 undefined(非严格模式下默认为全局对象)
thisArg = thisArg || window;
// 为 thisArg 创建一个临时唯一属性,避免属性冲突
const fnKey = Symbol('tempFn');
thisArg[fnKey] = this; // 将当前函数赋值给临时属性
const result = thisArg[fnKey](...args); // 调用函数
delete thisArg[fnKey]; // 删除临时属性
return result;
};
// 使用示例
greet.myCall(person, 'Bob'); // 输出: Hello, Bob! I'm Developer.
关键点说明
this绑定:通过将函数赋值给目标对象的临时属性,实现this的显式绑定。- 参数传递:使用剩余参数(
...args)接收动态参数列表。 - 清理临时属性:调用完成后删除临时属性,避免副作用。
应用场景
- 借用方法:例如借用数组方法处理类数组对象:
const arrayLike = { 0: 'a', 1: 'b', length: 2 }; Array.prototype.push.call(arrayLike, 'c'); // arrayLike 变为 { 0: 'a', 1: 'b', 2: 'c', length: 3 } - 继承与构造函数:在继承中调用父类构造函数:
function Parent(name) { this.name = name; } function Child(name) { Parent.call(this, name); }
注意事项
- 严格模式下,未指定
thisArg时this为undefined。 - 原始值(如数字、字符串)作为
thisArg时会被自动转换为对象(如new Number(1))。







