Home > database >  How to access one object in another object
How to access one object in another object

Time:12-05

I am busy creating an object. The end goal is that each evolution will link to a creature in another object.

let fresh = {
  botamon: {
    name: "Botamon",
    image: new URL("https://www.grindosaur.com/img/games/digimon-world/digimon/12-botamon.jpg"),
    stage: "Fresh",
    type: "Data"
  },
}

let inTraining = {
  koromon: {
    name: "Koromon",
    image: new URL("https://www.grindosaur.com/img/games/digimon-world/digimon/50-koromon.jpg"),
    stage: "In-Training",
    type: "Data",
    preDigivolution: fresh.botamon,
    line: rookie.agumon
  },
}

let rookie = {
  agumon: {
    name: "Agumon",
    Image: new URL("https://www.grindosaur.com/img/games/digimon-world/digimon/1-agumon.jpg"),
    Stage: "Rookie",
    Type: "Vaccine",
    PreDigivolution: inTraining.koromon
  },
}

The line: rookie.agumon throws an error, because the way this works is that koromon evolves to agumon so I have no idea why its throwing an error, the error is

digimon-digivolution.js:41 Uncaught ReferenceError: Cannot access 'rookie' before initialization

is it incorrect to call rookie.agumon in the koromon object?

CodePudding user response:

You are trying to resolve an identifier before its declaration. The variable is said to be in a TDZ (temporal dead-zone).

Trying to swap the declaration/initialization statements would still result in a similar ReferenceError: The identifier's resolution would still happen in its TDZ. With just the two statements it is impossible to create a circular reference.

Instead, you can separate the initializations into individual statements as @SebastianSimon suggested, where you assign the references afterwards. Example:

// Initialize separately
const koromon = {/*...*/};
const agumon = {/*...*/};

// Then assign to each other
koromon.digivolution = agumon;
agumon.preDigivolution = koromon;

Or you can use getters to avoid the problem of the TDZ, as @NickParsons suggests. This works because only upon access are we resolving the identifier, at which time we have already left its TDZ. Example:

const koromon = {
  name: "Koromon",
  get digivolution() { return agumon; }
};
const agumon = {
  name: "Agumon",
  get preDigivolution() { return koromon; }
};

console.log("Koromon's digivolution is:", koromon.digivolution.name);

  • Related