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");