2016-12-22 49 views
1

我正在製作一個tic-tac-toe遊戲,並且我正在嘗試讓我的x和o出現在單擊空格(div)時。我有我的系統,以便我的ticTacToe()對象「遊戲」可以通過它的對象原型進行更新。更新for循環內的javascript對象屬性?

的問題是,因爲我用一個for循環附加點擊事件處理所有的div與「空間」類,我不能在那個範圍內訪問了「遊戲」對象的屬性。如果我使用「this」,我會指的是div本身。我試着做一個原型功能和構造函數來更新「currentPlayer」,「板」和「轉」的遊戲對象的屬性,但我不能設法讓瀏覽器識別的屬性在遊戲中目的。

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(); 
} 

回答

0

綁定另一個變量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 
     } 
     }) 
    } 

那麼你可以參考game.boardgame.currentPlayer在事件偵聽器函數來訪問當前tictactoe objec噸。

+0

必須測試這個嗎?我不認爲它會起作用。我認爲根據他的代碼,你會提到函數,而不是對象。 – GeekAb

+0

@GeekAb當你'game.attachClicks()','this'指game'的'的值,這是該對象。 – Barmar

+0

'this'從來沒有提到Javascript中的函數。 – Barmar