I'm trying to make a simple tic tac toe game to learn and practice JavaScript OOP and am having some difficulties.
I would like to reference the game.turn value when firing the game.handleClick function. I know that using the this keyword references the scope of the thing being called, and in handleClick, the this refers to the game-tile-x being clicked. How can I reference object values that are outside of the 'handleClick' function scope?
Any help would be deeply appreciated!
<div id="game-board">
<div id="game-tile-1" class="game-tile"></div>
<!-- divs 2-8 -->
<div id="game-tile-9" class="game-tile"></div>
</div>
function Game() {
this.tiles = document.getElementsByClassName('game-tile'),
this.turn = 0;
this.init = function() {
for (let i = 0; i < this.tiles.length; i++) {
// reset game tiles
this.tiles[i].innerHTML = '';
// setup event listeners
this.tiles[i].addEventListener('click', this.handleClick);
}
};
this.handleClick = function() {
let id = parseInt(this.id.replace('game-tile-', ''));
console.log(id); // returns 0, 1, 2, etc.
console.log(this.turn); // returns undefined
};
}
let game = new Game();
game.init();
thisso you can reference it later when it's out of scope. ex:let ctx = this; this.init = function(){....ctx.tiles[i]}