call方法用于显式指定函数内部this指向的对象并立即执行,语法为func.call(thisArg, arg1, arg2...),常用于借用方法、实现继承及临时切换上下文,参数逐个传递,优先级高于隐式和默认绑定但低于new绑定。

call 方法用于在调用函数时,**显式指定该函数内部 this 指向的对象**,并立即执行函数。
基本语法和作用
格式:func.call(thisArg, arg1, arg2, ...)
其中:
-
thisArg:函数执行时 this 所绑定的对象;传
null或undefined时,在非严格模式下指向全局对象(如浏览器中是window),严格模式下为undefined - arg1, arg2, ...:依次传入函数的参数
常见使用场景
借用方法(函数复用)
比如让数组方法处理类数组对象:
立即学习“Java免费学习笔记(深入)”;
const arrayLike = {0: 'a', 1: 'b', length: 2};
Array.prototype.push.call(arrayLike, 'c'); // arrayLike 变成 {0:'a', 1:'b', 2:'c', length:3}
实现继承或临时切换上下文
让一个对象“借用”另一个对象的方法:
const person = { name: 'Alice' };
function introduce(age) {
console.log(`I'm ${this.name} and ${age} years old.`);
}
introduce.call(person, 25); // I'm Alice and 25 years old.
与 apply、bind 的区别
call 和 apply 都会立即调用函数,区别只在参数传递方式:
-
call(obj, a, b, c)—— 参数逐个列出 -
apply(obj, [a, b, c])—— 参数以数组形式传入
bind 不执行函数,而是返回一个新函数,其 this 被永久绑定(后续调用时不可更改):
const boundFn = func.bind(obj, 1); boundFn(2); // 等价于 func.call(obj, 1, 2)
注意 this 绑定优先级
显式绑定(call/apply/bind)的优先级高于隐式绑定(如 obj.method())和默认绑定,但会被 new 绑定 覆盖(使用 new 调用时,this 始终指向新创建的实例)。


















