-2

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();
DecPK
  • 24,537
  • 6
  • 26
  • 42
Mark
  • 1
  • 1
  • You can use `console.log(`The ${this.name} was founded in ${this.yearFounded} and its currency is ${this.details.currency}, with an ${this.details.symbol} symbol` );` and call the method as `america.details.printDetails.call(america);` – DecPK Jul 08 '21 at 23:47

1 Answers1

0

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks big time Bergi. Accessing it by explicitly referring to america helped. const america = { name: 'United State of America', yearFounded: 1776, details: { symbol: 'eagle', currency: 'USD', printDetails: function() { console.log(`The ${america.name} was founded in ${america.yearFounded} and its currency is ${this.currency}, with an ${this.symbol} symbol`); } } } – Mark Jul 09 '21 at 18:33