更新時間:2021-11-30 09:53:09 來源:動力節點 瀏覽827次
使用該call()方法,您可以編寫可用于不同對象的方法。
在 JavaScript 中,所有函數都是對象方法。
如果函數不是 JavaScript 對象的方法,則它是全局對象的函數。
下面的示例創建一個具有 3 個屬性的對象,firstName、lastName、fullName。
例子:
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
myObject.fullName();
在函數定義中,this指的是函數的“所有者”。
在上面的示例中,this是“擁有” fullName函數的person 對象。
換句話說,this.firstName表示這個對象的firstName 屬性。
該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"
}
// This will return "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"
}
// This will return "Mary Doe"
person.fullName.call(person2);
該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");
以上就是關于“調用JS函數”的介紹,大家如果想了解更多相關知識,可以關注一下動力節點的Java在線學習,里面的課程內容詳細,通俗易懂,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習