更新for循环内的javascript对象属性?

时间:2016-12-22 19:42:39

标签: javascript

我正在用javascript制作一个井字游戏,我现在正试图让我的x和o出现在我点击空格(div)时。我有我的系统,以便我的ticTacToe()对象"游戏"可以通过它的对象原型进行更新。

问题是因为我使用for循环将click事件处理程序附加到所有div,并使用" space"上课时,我无法访问"游戏"该范围内的对象。如果我使用"这个"我指的是div本身。我尝试过制作原型函数和构造函数来更新" currentPlayer"," board"和"转"游戏对象的属性,但我无法让浏览器识别出属性在游戏对象中。

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

1 个答案:

答案 0 :(得分: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对象。