मैं कक्षा में कोड के एक हिस्से को हर सेकेंड में बार-बार कॉल करने की कोशिश कर रहा हूं,
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
, मैं समझता हूं कि यह इस और सेटइंटरवल के साथ एक स्कोप इश्यू के कारण है, फिर भी मैं अनिश्चित हूं कि इस मुद्दे को हल करने के लिए बाइंड का उपयोग कैसे करें
संपादित करें: यहां प्रासंगिक कोड का पूरा टुकड़ा है
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);
-1
Robin Konold
29 अक्टूबर 2021, 12:33
2 जवाब
बस अंतराल लिखें जैसे:
const intervalRef = setInterval(() => { newGame.update() }, 1000);
0
Nick
29 अक्टूबर 2021, 12:46
आप अपने कंस्ट्रक्टर में अंतराल की घोषणा क्यों नहीं करते? इस तरह, आप किसी भी संदर्भ के मुद्दों से बचेंगे।
constructor() {
this.gameOver = false;
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
setInterval(this.update.bind(this), 1000); // Here
}
0
Jeremy Thille
29 अक्टूबर 2021, 12:47
this
की बेहतर समझ के लिए और आप जान सकते हैं कि आपके कोड में क्या गलत था।