call() 方法通过传递 this 和指定的参数值来调用一个 函数。
示例
//function that adds two numbers
function sum(a, b) {
return a + b;
}
// calling sum() function
var result = sum.call(this, 5, 10);
console.log(result);
//Output:
// 15
call() 语法
call() 方法的语法是:
func.call(thisArg, arg1, ... argN)
其中,func 是一个函数。
call() 参数
call() 方法可以接受 **两个** 参数:
thisArg-thisArg是在函数func中,this对象引用的对象。arg1, ... argN(可选) - 函数func的参数。
注意: 默认情况下,函数中的 this 指的是全局对象,即在 Web 浏览器中是 window,在 Node.js 中是 global。
call() 返回值
- 返回调用该函数时,使用指定的
this值和参数所获得的结果。
注意: 通过使用 call(),我们可以将一个对象拥有的函数分配给另一个对象并调用它。
示例 1:使用 call() 方法
function sum(a, b) {
return a + b;
}
// invoking sum() by passing this and 'a', 'b' arguments
let result = sum.call(this, 5, 3);
console.log(result);
输出
8
在上面的示例中,我们定义了一个返回两个数字之和的函数 sum()。
然后,我们使用 call() 方法调用 sum(),写法是 sum.call(this, 5, 3)。
在这里,默认情况下,函数内的 this 被设置为全局对象。
示例 2:使用和不使用 call() 方法
// function that finds product of two numbers
function product(a, b) {
return a * b;
}
// invoking product() without using call() method
let result1 = product(5, 2);
console.log("Return value Without using call() method: " + result1);
// invoking product() using call() method
let result2 = product.call(this, 5, 2);
console.log("Return value Using call() method: " + result2);
输出
Return value Without using call() method: 10 Return value Using call() method: 10
在上面的示例中,我们调用了 product() 函数:不使用 call() 和使用 call()。
- 不使用
call()- 我们可以直接调用product(),写法是product(5, 2)。 - 使用
call()- 我们必须将this参数传递进去,写法是product.call(this, 5, 2)。
示例 3:将对象作为 call() 中的 this 值传递
// object definition
const human = {
firstName: "Judah",
lastName: "Parker",
age: 26,
};
// function definition
function greet() {
const string = `My name is ${this.firstName} ${this.lastName}. I am ${this.age} years old.`;
console.log(string);
}
// passing object as this value in call() method
greet.call(human);
输出
My name is Judah Parker. I am 26 years old.
在上面的示例中,我们在 greet() 函数内部定义了一个变量 string,它可以访问 human 的值。
然后,我们将 human 对象作为 this 值传递给 call() 方法,写法是 greet.call(human),这将调用 greet()。
示例 4:使用 call() 链式调用构造函数
//function definition
function Animal(name, age) {
this.name = name;
this.age = age;
}
//function definition
function Horse(name, age) {
Animal.call(this, name, age);
this.sound = "Neigh";
}
//function definition
function Snake(name, age) {
Animal.call(this, name, age);
this.sound = "Hiss";
}
const snake1 = new Snake("Harry", 5);
console.log(snake1.name, snake1.age, snake1.sound);
const horse1 = new Horse("Arnold", 8);
console.log(horse1.name, horse1.age, horse1.sound);
输出
Harry 5 Hiss Arnold 8 Neigh
注意: call() 和 apply() 的区别在于,call() 接受一个参数列表,而 apply() 接受一个参数 数组。
另请阅读