Typescript: private member is suddenly undefined

北战南征 提交于 2019-12-20 03:38:09

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/17148360/typescript-private-member-is-suddenly-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!