Typescript: private member is suddenly undefined

前端 未结 1 1516
陌清茗
陌清茗 2021-01-22 14:17

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.

<
相关标签:
1条回答
  • 2021-01-22 14:45

    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.

    0 讨论(0)
提交回复
热议问题