JavaScript call() 函数
JavaScript call() 方法是 Function 对象的一个方法,通过 call() 调用函数可以指定函数内部 this 的值,这让函数/方法能在更多的场景下正确执行。
JavaScript call()
方法是 Function 对象的一个方法,通过 call()
调用函数可以指定函数内部 this
的值,这让函数/方法能在更多的场景下正确执行。
call()
与 apply()
类似,支持参数传递的方式不同, call()
方法接受是一个参数列表,而 apply()
接受的是包含多个参数的数组。
call()
用法:
functionName.call(thisValue, parameter1, parameter2, ...);
所有的参数都是非必须的,请根据实际的参数/方法的定义传递参数。
在 JavaScript 中,所有函数都属于一个对象。如果一个函数看起来不属于一个对象,那么它属于全局对象。
this 关键字
在函数定义中, this
指的是函数的“所有者”。
下面的示例创建一个具有 2 个属性和一个方法的对象。
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
// 返回 "John Doe":
person.fullName();
在上面的示例中, this
是拥有 fullName
函数的 person
对象。也就是说, this.firstName
代表 person
对象的 firstName
属性。
! 提示: 在 JS this 关键字阅读更多关于 this
的信息。
JavaScript call() 方法
call()
方法是 Function 对象的一个方法,所有的函数/方法都可以通过 call 调用。
使用 call()
,可以将方法中的 this
由一个对象改为另一个对象。
此示例实现了 person
的 fullName
方法中传入 person1
的值:
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
const person2 = {
firstName: "Mary",
lastName: "Doe",
};
// 返回 "John Doe":
person.fullName.call(person1);
此示例实现了 person
的 fullName
方法中传入 person2
的值:
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
const person2 = {
firstName: "Mary",
lastName: "Doe",
};
// 返回 "Mary Doe"
person.fullName.call(person2);
call() 方法的参数
call()
方法除了第一个参数接受 this 的值之外,还接受一个或多个参数的做为参数列表传递给原函数/方法。
call()
方法可以接受参数:
const person = {
fullName: function (city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
person.fullName.call(person1, "Oslo", "Norway");