类的定义如下:
export default class FishGame {
constructor(window) {
.......
this.window = window
......
}
gameloop() {
this.window.requestAnimationFrame(this.gameloop);
var now = Date.now();
this.deltaTime = now - this.lastTime;
this.lastTime = now;
....
}
}
你可以看到gameloop函数是一个递归调用。我以这种方式调用此函数:
function game() {
let fishGame = new FishGame(this);
fishGame.gameloop();
}
当抛出异常时,谁能告诉我为什么这个对象是空的?:
发布于 2018-08-12 12:27:55
问题是this
在回调中丢失了。在this post中描述了几种干净的方法。一种方法是将this
绑定到回调,或者使用自动绑定了this
的箭头函数:
class FishGame {
constructor() {}
gameloop() {
requestAnimationFrame(() => this.gameloop());
console.log(Date.now());
}
}
new FishGame().gameloop();
发布于 2018-08-12 12:24:19
class FishGame {
static loop(game) {
function doloop() {
requestAnimationFrame(doloop)
game.gameloop()
}
doloop()
}
constructor() {
self = this;
this.name = "Lamax"
}
gameloop() {
console.log(Date.now()+": "+this.name);
}
}
FishGame.loop(new FishGame());
问题是您正在调用此函数,在requestAnimationFrame中作为参数传递的函数中,尝试上面的代码片段
https://stackoverflow.com/questions/51805603
复制相似问题