2016-12-22 14 views
1

私はjavascriptでtic-tac-toeのゲームを作っています。私は現在、スペース(divs)をクリックするとxとoを表示しようとしています。私は私のシステムを持っているので、私のticTacToe()オブジェクト "game"はオブジェクトのプロトタイプを通じて更新することができます。forループ内のjavascriptオブジェクトのプロパティを更新しますか?

問題は、「スペース」クラスのすべてのdivにクリックイベントハンドラをアタッチするためにforループを使用しているため、そのスコープで「ゲーム」オブジェクトのプロパティにアクセスできません。私が "これ"を使用する場合、私はdiv自体を参照しています。ゲームオブジェクトの "currentPlayer"、 "board"、 "turn"プロパティを更新するためのプロトタイプ関数とコンストラクタ関数を作成しようとしましたが、プロパティがゲーム内にあることをブラウザに認識させることはできませんオブジェクト。

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 t。

+0

これをテストしましたか?私はそれが動作するとは思わない。彼のコードによれば、これはオブジェクトではなく関数を参照すると思います。 – GeekAb

+0

@GeekAb 'game.attachClicks()'を実行すると、 'this'はオブジェクトである' game'の値を参照します。 – Barmar

+0

'this'はJavascriptの関数を決して参照しません。 – Barmar

関連する問題