0

我这里有一些奇怪的行为,在渲染的 JS 中,update 方法中 this 的值是 window,但它应该是 Game(如在 onKeyDown 方法中)。你如何纠正这个?

class Game {

    //for the key events
    rightDown: bool = false;

    constructor() {

    }


    onKeyDown(evt) {
        if (evt.keyCode == 39) this.rightDown = true;
        else if (evt.keyCode == 37) this.leftDown = true;
        if (evt.keyCode == 32) {
            this.space = true;
            var bullet = new GameObjects.GameObjects.Bullet(10);
            this.addProjectile(bullet);
        };
    }



    update(elapsed: number) {

   if (this.rightDown) {
            console.log(this.rightDown);
        }
}
4

1 回答 1

3

你在其他地方写过这样的东西:

setupAnimationTimer(myGame.update); // Maybe window.requestAnimationFrame ?

请注意,您只是传递updatefromGame的原型——没有指向实际myGame实例的指针,因此执行回调的人无法使用正确的指针正确调用您的update方法。this

如果您四处搜索,有很多关于this绑定如何丢失或保留的博客文章;这里有两种可能的解决方案:

// Create a new closure
setupAnimationTimer(() => myGame.update());

或者

// Create a new function object that always invokes with the given 'this' value
setupAnimationTimer(myGame.update.bind(myGame));
于 2013-02-25T17:35:35.847 回答