0

I'm new to TypeScript, coming from Java and having some knowledge of JavaScript. I'm learning TS by making a good old Snake game!

I have this class Gui that should draw the canvas. In my contructor I start with creating my Snake object. Later on I start the game loop in which the Snake should be moved...

But the loop function does not work, because of this error. "Uncaught Type Error: Cannot read property 'move' of undefined."

I suspect it has something to do with the setInterval function that works 'asyncronously' or something but I'm not sure... It seems as a kind of fundamental JavaScript problem.

Any help is highly appreciated!

module gui {

    export class Gui {
        snake:model.Snake;
        loop:any;

        constructor() {
            // get snake
            this.snake = new model.Snake();

            // Attach key event
            document.addEventListener("keydown", KeyListener.handleEvt);

            // activate game loop
            this.loop = setInterval(this.gameLoop, 50);
        }

        gameLoop() {
            if (this.snake) {
                console.log("loop");
                this.snake.move();
                this.drawSnake()
            }
        }

        drawPart(part:model.Part) { ... }

        drawSnake() { ... }

    }

    class KeyListener {

        static handleEvt(e) {
            if (e) {
                switch (e.keyCode) {
                    case 37:
                        console.log("left");
                        break;
                    case 38:
                        console.log("up");
                        break;
                    case 39:
                        console.log("right");
                        break;
                    case 40:
                        console.log("down");
                        break;
                }
            }
        }

    }

}
olefrank
  • 6,452
  • 14
  • 65
  • 90
  • Oh the dreaded "this in callbacks" problem.....! I found this description on the setInterval Mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval. I ended up using the arrow syntax (ES6). It did the trick! this.loop = setInterval(() => this.gameLoop(), this.loopSpeed); – olefrank Apr 01 '15 at 15:45

1 Answers1

2

Change:

this.loop = setInterval(this.gameLoop, this.loopSpeed);

To:

this.loop = setInterval(() => this.gameLoop(), this.loopSpeed);

The value of this was getting lost when you passed in the function directly.

David Sherret
  • 101,669
  • 28
  • 188
  • 178