未捕获的TypeError:无法读取未定义的属性“2”

时间:2015-02-04 18:11:12

标签: javascript jquery

以下是TicTacToe程序的代码。我正在努力写OO。我得到一个Uncaught TypeError:当我点击网格上的一个框时,无法在checkIfPositionIsTaken函数中读取未定义的属性'2'。

以下是TicTacToe对象的构造函数:

var TicTacToe = function () {

this.player1Name = "Player 1";
this.player2Name = "Player 2";
var turn = "";
var grid = [[0,0,0],[0,0,0],[0,0,0]];
var hasWinner = 0;
var moveCount = 0;
}

以下是checkIfPositionIsTaken函数。我相信错误是在this.grid上,但它是在创建对象时定义的。

// Check If Position Is Taken
TicTacToe.prototype.checkIfPositionIsTaken = function(row, col){
   if(this.grid[row][col] !== 0){
      alert("This position is taken. Please try other position.");
      return true;
}
else{
    return false;
}
};

以下是我创建TicTacToe对象的地方:

var theGame = new TicTacToe();

以下是我点击网格上的框的事件:

// Column click event
$(".col").click(function(){

    var row = $(this).parent().index();
    var col = $(this).index();

    if(theGame.checkIfPositionIsTaken(row, col) == false &&       theGame.checkIfGameHasEnded() == false){

if(theGame.turn == theGame.player1Name){

    $(this).text(theGame.drawO(row, col));

    if(theGame.winnerCheck(1,theGame.player1Name) == false && theGame.checkIfGameIsADraw() == false){
           theGame.turn = theGame.player2Name;
           theGame.setBoardMsg(theGame.player2Name+"'s turn now!");
        }
        return; 
    }
else{

    $(this).text(theGame.drawX(row, col));

    if(theGame.winnerCheck(2,theGame.player2Name) == false && theGame.checkIfGameIsADraw() == false){
           theGame.turn = theGame.player1Name;
           theGame.setBoardMsg(theGame.player1Name+"'s turn now!");
        }
        return; 
        }
}
});

这是我的第一个问题,如果您需要更多信息,请告诉我。感谢。

1 个答案:

答案 0 :(得分:0)

var grid = [[0,0,0],[0,0,0],[0,0,0]];

gridTicTacToe方法的“本地”变量,因此this.grid将是未定义的。

turnhasWinnermoveCount会遇到同样的问题。