Home > Software engineering >  How can I access an instance of a class from a child instance?
How can I access an instance of a class from a child instance?

Time:08-29

I have a class named "Main", with one instance named "main". The "main" instance has two properties that are instances of other classes, named "player" and "background". I want the child instances to be able to use each other, as well as the "main" instance. Below is my attempt, which throws an error: "main is undefined".

class Player {
    constructor() {
    }

    x = 10;
    y = 20;
};

class Background {
    constructor() {
    }

    backgroundCenterX = main.player.x;
    backgroundCenterY = main.player.y;
    // the previous two lines throw an error
};

class Main {
    constructor() {
        this.background = new Background();
        this.player = new Player();
    }
};

var main = new Main();

I have tried a few things, including passing the "main" instance by reference to the constructors of the child instances, but I haven't been able to get it to work. I think the code is throwing an error because the "Main" constructor hasn't finished running when the "main" instance is referenced.

Is there any way to fix this?

CodePudding user response:

You can pass the main into the child constructors. But the order matters, you have to construct and assign the player first if the background constructor is to access it on main.

class Player {
    constructor(main) {
      this.main = main;
    }
    

    x = 10;
    y = 20;
};

class Background {
    constructor(main) {
      this.main = main;
      this.backgroundCenterX = this.main.player.x;
      this.backgroundCenterY = this.main.player.y;
    }
};

class Main {
    constructor() {
        this.player = new Player(this);
        this.background = new Background(this);
    }
};

var main = new Main();

console.log(main);

CodePudding user response:

You can pass the main instance to the Constructor of Player and Background.

Then you can access it via this.main

class Player {
    constructor(main) {
      this.main = main;
    }

    x = 10;
    y = 20;
};

class Background {
    constructor(main) {
      this.main = main;
    }

    doSomeThing() {
      const backgroundCenterX = this.main.player.x;
      const backgroundCenterY = this.main.player.y;
      console.log(backgroundCenterX, backgroundCenterY);
    }
    
};

class Main {
    constructor() {
        this.background = new Background(this);
        this.player = new Player(this);
    }

    doSomeThing() {
      this.background.doSomeThing();
    }
};

var main = new Main();
main.doSomeThing()
  • Related