简体   繁体   中英

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

The name and the founding year are not part of the object on which you are calling the method, but some other object. You can access it by explicitly referring to america.… , there is no way to access it through the this keyword . The this value in your method call refers to the details object only.

Alternatively, move the printDetails method to the outer object (so that you can call america.printDetails() instead of america.details.print() ), and use this.name and this.details.currency respectively. Or just flatten the entire structure into a single object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM