When I call newTarget from the tileClick function in class Game I get the error "Uncaught TypeError: this.newTarget is not a function", but when I run it from the function Start I don't get an error and I really don't understand why
Here's my javascript code:
function Start() {
tiles = document.querySelectorAll(".tile");
var game = new Game(600, 15000, tiles, "playername");
tiles.forEach((tile) => {
tile.addEventListener("click", game.tileClick);
tile.isTarget = false;
tile.style.background = "grey";
});
game.newTarget();
}
class Game {
constructor(interval, maxTime, tiles, player) {
this.points = 0;
this.player = player;
this.maxTime = maxTime;
this.interval = interval;
this.tiles = tiles;
this.startTime = Date.now();
document.getElementById("points").textContent = this.points;
}
newTarget() {
if (Date.now() - this.startTime > this.maxTime) {
clearInterval(this.timer);
alert("Game over, you got: " + this.points + " points!");
return;
}
tiles.forEach((tile) => {
tile.isTarget = false;
tile.style.background = "grey";
});
var target = Math.floor(Math.random() * tiles.length);
tiles.item(target).isTarget = true;
tiles.item(target).style.background = "red";
this.timer = setInterval(this.newTarget, this.interval);
}
tileClick(event) {
if (Date.now() - this.startTime > this.maxTime) {
return;
}
this.tile = event.target;
if (this.tile.isTarget) {
console.log(this.points);
this.points++;
document.getElementById("points").textContent = this.points;
clearInterval(this.timer);
this.newTarget();
}
}
}