I'm making a tic-tac-toe game in javascript and i'm currently trying to get my x's and o's appear when I click on the spaces (divs). I have my system so that my ticTacToe() object "game" can update through it's object prototype.
The problem is since I use a for loop to attach click event handlers to all the divs with the "space" class, I can't access the properties of the "game" object at that scope. If I use "this" i'd be referring to the div itself. I've tried making a prototype function and a constructor function to update the "currentPlayer", "board" and "turn" properties of the game object but I can't manage to get the browser to recognize that the properties are in the game object.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="js/script2.js"></script>
</head>
<body>
<div id="gameBoard">
<h1 id="msg">Welcome to Tic-Tac-Toe</h1>
<div id="tl" class="space"></div>
<div id="tm" class="space"></div>
<div id="tr" class="space"></div>
<div id="ml" class="space"></div>
<div id="mm" class="space"></div>
<div id="mr" class="space"></div>
<div id="bl" class="space"></div>
<div id="bm" class="space"></div>
<div id="br" class="space"></div>
</div>
</body>
</html>
JS
function ticTacToe() {
this.board = [[0,0,0]
[0,0,0]
[0,0,0]];
this.turn = 0;
this.currentPlayer = 1;
}
ticTacToe.prototype = {
status: function(){
console.log("The number of turns played is " + this.turn +
" and it is player " + this.currentPlayer + "'s turn.");
},
attachClicks: function(){
var spaces = document.getElementsByClassName("space"),
player = this.currentPlayer;
for(var i = 0; i<spaces.length; i++){
spaces[i].addEventListener('click',function(){
if(player == 1){
this.style.backgroundImage = "url('x.png')";
//Update ticTacToe's turn, player, and board
}
else {
this.style.backgroundImage = "url('o.png')";
//Update ticTacToe's turn, player, and board
}
})
}
}
}
var game = new ticTacToe();
window.onload = function(){
game.attachClicks();
}
Bind another variable to this
:
attachClicks: function(){
var game = this;
var spaces = document.getElementsByClassName("space")
for(var i = 0; i<spaces.length; i++){
spaces[i].addEventListener('click',function(){
if(player == 1){
this.style.backgroundImage = "url('x.png')";
//Update ticTacToe's turn, player, and board
}
else {
this.style.backgroundImage = "url('o.png')";
//Update ticTacToe's turn, player, and board
}
})
}
Then you can refer to game.board
and game.currentPlayer
in the event listener function to access the current tictactoe
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.