我試圖每秒一遍又一遍地呼叫類中的一部分代碼,
update() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
entity.y = 1;
renderAliens(entity, this.context);
}
}
}
這是我試圖在我的游戲物件中呼叫的代碼
setInterval(newGame.update(),1000),但是當我嘗試這樣做時,它錯誤地說Uncaught TypeError: this.entities is undefined,我知道這是由于 this 和 setinterval 的范圍問題,但我不確定如何使用系結解決問題
編輯:這是整段相關代碼
class Game {
constructor() {
this.gameOver = false;
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
}
start() {
this.entities.push(new Ship(0, 400));
this.entities.push(new Alien(1, 0));
this.entities.push(new Alien(20, 0));
this.entities.push(new Alien(40, 0));
}
render() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
renderAliens(entity, this.context);
} else if (entity instanceof Ship) {
renderShip(entity, this.context);
}
}
}
update() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
entity.y = 20;
renderAliens(entity, this.context);
}
}
}
endGame() {}
}
const newGame = new Game();
newGame.start();
newGame.render();
let t = setInterval(newGame.update, 1000);
uj5u.com熱心網友回復:
您有兩個選擇:
- 使用
.bind(). 這系結this到 newGame 實體setInterval(newGame.update.bind(newGame), 1000); - 定義回呼函式:
setInterval(function(){ newGame.update(); }, 1000);
uj5u.com熱心網友回復:
只需將間隔寫為:
const intervalRef = setInterval(() => { newGame.update() }, 1000);
uj5u.com熱心網友回復:
為什么不在建構式中宣告間隔?這樣,您將避免任何背景關系問題。
constructor() {
this.gameOver = false;
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
setInterval(this.update.bind(this), 1000); // Here
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341030.html
標籤:javascript 这个 设置间隔
上一篇:Keras:'TypeError:Failedtoconverttheobjectoftype<class'tuple'>toTensor'當我構建
下一篇:我可以在數字中轉換NaN嗎?
