Description:
I am using window.addEventListener() and want to call a named function (not an anonymous function) as I want to be able to use removeEventListener at a later stage..
However, the console.log inside the eventHandler which is an arrow function reveals that "this" still points to the window object instead of game object.
PS: Ignore the other parts of the code as I was refactoring this, and rest might be still incomplete, I know I can use constructors, but I am in a learning phase and before I study constructors I wanted to see if this can be done without the constructor
function makeGameObject() {
return {
score: 0,
level: 1,
start() {
for (let coin of coins) {
this.moveCoin(coin);
}
window.addEventListener("keydown", this.gameOn)
},
stop() {
window.removeEventListener("keydown", this.gameOn);
},
gameOn: (evt) => {
console.log(this);
if (evt.key.toUpperCase() === "W" || evt.key === "ArrowUp") {
this.moveObject(player, 30, 'up');
} else if (evt.key.toUpperCase() === "S" || evt.key === "ArrowDown") {
this.moveObject(player, 30, 'down');
} else if (evt.key.toUpperCase() === "A" || evt.key === "ArrowLeft") {
this.moveObject(player, 30, 'left');
player.style.transform = 'scale(-1,1)';
} else if (evt.key.toUpperCase() === "D" || evt.key === "ArrowRight") {
this.moveObject(player, 30, 'right');
player.style.transform = 'scale(1,1)';
}
for (let coin of coins) {
if (this.isTouching(player, coin)) {
this.moveCoin(coin);
score++;
h1.innerText = score;
}
}
},
here is the call for the function:
const player = document.querySelector("#player");
const coins = document.querySelectorAll(".coin");
const body = document.querySelector("body");
const h1 = document.querySelector("h1");
const game = makeGameObject();
game.start();