簡體   English   中英

在使用“this”關鍵字的方法中,如何從其他屬性訪問對象屬性?

[英]How do I access the object properties from other properties, while within a method using the 'this' keyword?

 const america = { name: 'United State of America', yearFounded: 1776, details: { symbol: 'eagle', currency: 'USD', printDetails: function() { console.log(`The ${this.name} was founded in ${this.yearFounded} and its currency is ${this.currency}, with an ${this.symbol} symbol`); } } } america.details.printDetails();

名稱和創建年份不是調用方法的對象的一部分,而是其他對象的一部分。 您可以通過顯式引用america.…來訪問它america.… ,無法通過this關鍵字訪問它。 方法調用中的this值僅指details對象。

或者,將printDetails方法移動到外部對象(以便您可以調用america.printDetails()而不是america.details.print() ),並分別使用this.namethis.details.currency 或者只是將整個結構展平成一個單一的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM