call方法用于显式绑定函数的this指向并按顺序逐个传入参数,语法为func.call(thisArg, arg1, arg2, ...),其中thisArg指定this值,后续参数依次对应函数形参。

call 是 JavaScript 中实现显式绑定(explicit binding)的核心方法之一,它能强制指定函数内部 this 的指向,并**按顺序逐个传入参数**。
call 的基本语法和参数传递方式
调用形式为:func.call(thisArg, arg1, arg2, arg3, ...)
- thisArg:函数执行时 this 指向的对象(null/undefined 在非严格模式下会自动转为全局对象,严格模式下保持原值)
- arg1, arg2, ...:从第二个参数开始,每个都作为实参,**依次传给被调用函数的形参**
实际例子:对比普通调用与 call 调用
假设有一个函数:
function introduce(name, age) {
console.log(`我是${name},今年${age}岁,来自${this.city}`);
}有对象:
const person = { city: '杭州' };使用 call 显式绑定并传参:
introduce.call(person, '小明', 25); // 输出:我是小明,今年25岁,来自杭州
这里 person 成为 this,'小明' 和 25 分别对应 name 和 age。
注意:参数必须逐个列出,不支持数组直接展开(除非配合扩展运算符)
如果参数存在变量中(比如一个数组),不能直接传数组:
const args = ['小红', 28]; introduce.call(person, args); // ❌ 错误:args 整体变成第一个参数,age 为 undefined
正确做法是手动展开或改用 apply(它接受参数数组):
introduce.call(person, args[0], args[1]); // ✅ 手动拆解 // 或 introduce.apply(person, args); // ✅ apply 支持数组参数 // 或(ES6+) introduce.call(person, ...args); // ✅ 使用扩展运算符
常见用途场景
- 借用其他对象的方法(如数组方法处理类数组对象):
Array.prototype.slice.call(arguments) - 实现继承时调用父构造函数:
Parent.call(this, name, age) - 临时切换上下文执行函数,避免修改原对象
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











