0

I'm trying to acess GameManager instance.levels but always returns as undefined.
I could't use this.instance because it belongs to GM

class GameManager { 
    instance = { levels: { } }
    constructor(){ 

    }

    Level = class { /* extends ENGINE.Container, ENGINE IS NOT MINE */
        constructor(name) {
            // super(); /* EXTENDS ENGINE.CONTAINER */
            
            instance.levels[name] = this; /* new ENGINE.Container(); */
        }

        tick = function(){ /* will be overridden */}
    }
}

const game = new GameManager();
var loadScreen = new game.Level('ls');
loadScreen.tick = function(){
  
}
4
  • Why are you nesting classes like this? Jul 24, 2021 at 14:44
  • @evolutionxbox does it really matter why?
    – vanowm
    Jul 24, 2021 at 14:46
  • What do you mean? shouldn't i use like that?
    – dgrfps
    Jul 24, 2021 at 14:48
  • 1
    It might solve your issue. Why not pass the game instance into the constructor for Level? loadScreen = new Level('ls', game)? Jul 24, 2021 at 14:48

1 Answer 1

1

While nesting classes itself is already a bit hacky, you can get even hackier and use an IIFE to expose the GameManager as a scoped variable:

class GameManager {
    instance = { levels: {} }
    constructor() {

    }

    Level = (instance => class {
        constructor(name) {
        }

        getGame = () => instance;
    })(this);
}

const game = new GameManager();
var loadScreen = new game.Level('ls');
console.log(loadScreen.getGame());

But again, might be better off not nesting the classes and instead using a factory method, e.g. loadScreen = game.createLevel('ls'). The factory method could then call the non-nested version like new Level(game, 'ls').

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.