JavaScript Function call()
方法重用
使用 call()
方法,您可以编写一个可用于不同对象的方法。
所有函数都是方法
在 JavaScript 中,所有函数都是对象的方法。
如果一个函数不是 JavaScript 对象的某个方法,那么它就是全局对象的一个函数(请参阅前一章)。
下面的示例创建一个包含 3 个属性的对象:firstName、lastName、fullName。
示例
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// 这将返回 "John Doe"
person.fullName();
自己动手试一试 »
在上面的示例中,this
指的是 person 对象。
this.firstName 表示 this 的 firstName 属性。
等同于
this.firstName 表示 person 的 firstName 属性。
什么是 this?
在 JavaScript 中,this
关键词指向一个对象。
this
关键词指向不同的对象,具体取决于它的使用方式。
在对象方法中,this 指向对象。 |
单独使用时,this 指向全局对象。 |
在函数中,this 指向全局对象。 |
在严格模式下的函数中,this 是 undefined 。 |
在事件中,this 指向接收事件的元素。 |
诸如 call() 、apply() 和 bind() 等方法可以将 this 指向任何对象。 |
JavaScript call() 方法
call()
方法是一个预定义的 JavaScript 方法。
它可用于调用(执行)一个方法,并将一个拥有对象作为参数。
使用 call()
,一个对象可以使用属于另一个对象的方法。
此示例调用 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()
方法可以接受参数
示例
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");