Pregunta

So, I've got a basic Typescript application, that shouldn't actually cause any major problems, but it seems, that something's going wrong here and I have no idea what.

I do have this private member minUpdateRate in my GameContainer class, that is initialized in the constructor. This seems to go well, because when GameContainer.start() is called, the console.log() method will print out 1.

However, when the GameContainer.render() method is called, it seems to be out of the scope or something, the log method outputs undefined there.

I'm pretty new to TypeScript and not that deep into JavaScript either (especially when it comes to scopes, it's getting confusing to me :/). How can I however solve this?

Main class:

class TwoDGame extends Game {
    public static main(context:CanvasRenderingContext2D) {
        var game:Game = new TwoDGame();
        var container:GameContainer = new GameContainer(context, game);

        container.start();

        return game;
    }
}

Game Container class:

class GameContainer {
    ...
    private minUpdateRate:number;
    private game:Game;
    private time:number;
    ...

    constructor(context:CanvasRenderingContext2D, game:Game) {
        ...
        this.minUpdateRate = 1;
        this.game = game;
    }

    public start() {
        ...
        console.log(this.minUpdateRate);
    }

    public render() {
        var now:number = new Date().getMilliseconds();
        var delta:number = now - this.time;
        console.log(this.minUpdateRate);

        if (delta > this.minUpdateRate) {
            ...
        }
    }
}

Render is called via setInterval in the script area:

var game = TwoDGame.main(context);

setInterval(game.getGameContainer().render, 16);
¿Fue útil?

Solución

You're losing the object context when you pass setInterval() a reference to the "render" method that way.

setInterval(function() { game.getGameContainer().render(); }, 16);

There's no intrinsic relationship between a function and an object that refers to it via a property value. By using an anonymous function, you can ensure that the "container" object will be the value of this inside "render".

You could also do this with the .bind() method of the Function prototype:

setInterval(game.getGameContainer().render.bind(game.getGameContainer()), 16);

but that seems a little ugly in this case.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top