call 实现 js
使用 call 方法实现函数调用
call 是 JavaScript 中函数对象的一个方法,用于显式指定函数执行时的 this 值,并传递参数。其语法如下:
function.call(thisArg, arg1, arg2, ...)
thisArg 是函数运行时绑定的 this 值,arg1, arg2, ... 是传递给函数的参数列表。
基本用法示例
function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
name: 'Alice'
};
greet.call(person, 'Bob'); // 输出: Hello, Bob! My name is Alice.
修改 this 绑定
call 的主要用途是动态改变函数内部的 this 指向。以下是一个对象方法借用示例:
const obj1 = {
value: 10,
getValue: function() {
return this.value;
}
};
const obj2 = {
value: 20
};
console.log(obj1.getValue.call(obj2)); // 输出: 20
传递多个参数
call 可以传递多个参数给目标函数:
function add(a, b) {
return a + b + this.c;
}
const context = { c: 3 };
console.log(add.call(context, 1, 2)); // 输出: 6 (1+2+3)
实现继承
call 常用于构造函数继承中:
function Parent(name) {
this.name = name;
}
function Child(name, age) {
Parent.call(this, name); // 调用父类构造函数
this.age = age;
}
const child = new Child('Tom', 5);
console.log(child.name); // 输出: Tom
类数组对象处理
call 可以将类数组对象转换为真正的数组:
function listToArray() {
return Array.prototype.slice.call(arguments);
}
const arr = listToArray(1, 2, 3);
console.log(arr); // 输出: [1, 2, 3]
注意事项
- 如果
thisArg为null或undefined,在非严格模式下会自动替换为全局对象 - 严格模式下
thisArg不会被强制转换 call会立即执行函数,与bind不同
与 apply 的区别
call 和 apply 功能相似,主要区别在于参数传递方式:
function sum(a, b, c) {
return a + b + c;
}
// call 逐个传递参数
sum.call(null, 1, 2, 3);
// apply 以数组形式传递参数
sum.apply(null, [1, 2, 3]);






