martinde Posted February 18, 2016 Share Posted February 18, 2016 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 More sharing options...
Tom Atom Posted February 18, 2016 Share Posted February 18, 2016 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(); }; martinde 1 Link to comment Share on other sites More sharing options...
martinde Posted February 20, 2016 Author Share Posted February 20, 2016 Thank you, your code solved my problem! Link to comment Share on other sites More sharing options...
Recommended Posts