以下是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;
}
}
});
这是我的第一个问题,如果您需要更多信息,请告诉我。感谢。
答案 0 :(得分:0)
var grid = [[0,0,0],[0,0,0],[0,0,0]];
grid
是TicTacToe
方法的“本地”变量,因此this.grid
将是未定义的。
turn
,hasWinner
,moveCount
会遇到同样的问题。