所以,我想創建一個函式來做一些事情,然后在稍后創建的不同物件中使用相同的函式。
下面的代碼中有兩個實體:測驗 (01) 和注釋掉 (02),反之亦然。
"use strict";
function fullName() {
return this.firstName " " this.lastName;
}
const person = {
firstName: "Anant",
lastName: "Ghotale"
completeName: fullName.call(person) // (01) does not work
};
//person.completeName = fullName.call(person); (02) this works
console.clear();
console.log(person.completeName);
(02) 有效,但 (01) 無效。
也就是說,person在使用呼叫 put this = person 的同時在外部創建一個新屬性可以作業,但不能在它內部使用。
這些是我的問題:
- 如何在物件內使用(呼叫)函式?
- 在物件內部呼叫函式是愚蠢的嘗試嗎?有沒有更好的方法來完成同樣的任務?
uj5u.com熱心網友回復:
您可能想為此使用吸氣劑。
function fullName() {
return this.firstName " " this.lastName;
}
const person = {
firstName: "Anant",
lastName: "Ghotale",
get completeName() {
return fullName.call(this)
}
};
console.log(person.completeName)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327727.html
標籤:javascript 功能 目的 称呼
