Jump to content

Acces my own class methods within create()


martinde
 Share

Recommended Posts

I have a question regarding Typescript an `this`:

 

    class Calculator {
        foo: number;
    
        constructor(foo: number) {
            this.foo = foo;
        }
    
        public write() {
            return "abc";
        }
    }

Now I create an instance in my Game and want to call its method, but this.calc is undifined:

   

 class Game {
     
        calc: Calculator;
     
        constructor() {
            // this is working fine
            this.calc = new Calculator(1);
        }
      
        create() {
             for (var index = 0; index < 5; index++) {
                // here this.calc is undefined and I don't know why
            }      
        } 
    }

Then in my create method I always get `this.calc` is `undefined`and I dont know why.

Link to comment
Share on other sites

Hi, I do exactly this in my games (also Typescript) and it works. Are you sure you called new on your Game class before it gets into create?

I also recommend to clearly split state from game to make things clear. Try following example:

// -------------------------------------------------------------------------
class Calculator {

    // -------------------------------------------------------------------------
    public sayHello() : void {
         console.log("Hello!");
    }
}


// -------------------------------------------------------------------------
class Game extends Phaser.Game {

    // -------------------------------------------------------------------------
    constructor() {
        // init game
        super(640, 400, Phaser.CANVAS, "content", null);

        this.state.add("State", State);

        this.state.start("State");
    }
}

// -------------------------------------------------------------------------
class State extends Phaser.State {

    private _calc: Calculator();

    // -------------------------------------------------------------------------
    constructor() {
         this._calc = new Calculator();
    }

    // -------------------------------------------------------------------------
    create() {
         this._calc.sayHello();
    }
}

// -------------------------------------------------------------------------
window.onload = () => {
    new Game();
};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...