javascript - Object undefined when declared before setInterval function -
this question has answer here:
i'm new typescript, coming java , having knowledge of javascript. i'm learning ts making old snake game!
i have class gui should draw canvas. in contructor start creating snake object. later on start game loop in snake should moved...
but loop function not work, because of error. "uncaught type error: cannot read property 'move' of undefined."
i suspect has setinterval function works 'asyncronously' or i'm not sure... seems kind of fundamental javascript problem.
any highly appreciated!
module gui { export class gui { snake:model.snake; loop:any; constructor() { // 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; } } } } }
change:
this.loop = setinterval(this.gameloop, this.loopspeed);
to:
this.loop = setinterval(() => this.gameloop(), this.loopspeed);
the value of this
getting lost when passed in function directly.
Comments
Post a Comment