[英]Get a property value from an object calling object itsself instead of its property name
我想知道在 Javascript 中是否有一種方法可以訪問 object 的屬性值(使用吸氣劑正確設置),只需鍵入其 object 名稱而無需鍵入 'object.property'。 我到目前為止嘗試的是這樣的:
let person = {
get () {return this.name + this.lastname},
name: 'John',
lastname: 'Doe'
}
console.log (person);
但我總是得到整個 object 而不是我想要的 getter 屬性。 有任何想法嗎? 謝謝!
覆蓋.toString()
方法,然后強制將 object 轉換為字符串,以強制調用.toString()
方法。
像這樣:
let person = { toString: function() {return this.name + " " + this.lastname}, name: 'John', lastname: 'Doe' } console.log('Person: ' + person); console.log(''+person); console.log(person.toString()); console.log(person+'');
筆記:
function
關鍵字(不能使用箭頭功能)。console.log(person)
仍將 output object 結構,因為沒有什么可以強制調用.toString()
。首先:我提供的選項都不能完全滿足您的要求(據我所知,在 JS 中無法完成)。
話雖如此,您可以在此處使用toString()
方法,但這僅在您調用person
的操作需要字符串強制時才有效。
您還可以隨時解構對象,以便只獲得所需的屬性。
兩者都顯示在此示例中:
let p = { toString: function() { return `${this.name} ${this.lastname}` }, name: 'John', lastname: 'Doe' } // forcing toString() call console.log(`${p}`); // logging the actual object console.log(p); // using destructuring const { name, lastname } = p, person = `${name} ${lastname}`; console.log(person);
或者,您可以使用Person
class 以及 getter 和解構:
class Person { constructor(name, lastname) { this.name = name; this.lastname = lastname; } get person() { return `${this.name} ${this.lastname}`; } } const { person } = new Person('John', 'Doe'); console.log(person);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.