call js实现
JavaScript 调用方法
使用 call() 方法可以调用一个函数,并指定函数内部的 this 值以及传递参数。call() 方法的语法如下:

function.call(thisArg, arg1, arg2, ...)
thisArg:在函数运行时指定的this值。arg1, arg2, ...:传递给函数的参数列表。
示例代码
function greet(name, age) {
console.log(`Hello, ${name}! You are ${age} years old.`);
console.log(`This context is:`, this);
}
const person = {
country: 'USA'
};
greet.call(person, 'Alice', 30);
运行结果:

Hello, Alice! You are 30 years old.
This context is: { country: 'USA' }
应用场景
- 显式绑定
this值:当需要明确指定函数执行时的上下文时,可以使用call()。 - 借用方法:可以通过
call()调用其他对象的方法。
const obj1 = {
value: 10,
getValue: function() {
return this.value;
}
};
const obj2 = {
value: 20
};
console.log(obj1.getValue.call(obj2)); // 输出 20
与 apply() 的区别
call() 和 apply() 功能类似,但传递参数的方式不同:
call()逐个传递参数。apply()以数组形式传递参数。
function sum(a, b, c) {
return a + b + c;
}
console.log(sum.call(null, 1, 2, 3)); // 6
console.log(sum.apply(null, [1, 2, 3])); // 6
注意事项
- 如果
thisArg为null或undefined,在非严格模式下会默认指向全局对象(如window),严格模式下则为undefined。 call()不会复制原函数,而是直接调用它。






