【发布时间】:2015-04-04 09:20:53
【问题描述】:
以下是井字游戏程序的代码。我正在尝试编写 OO。我得到一个未捕获的类型错误:当我单击网格上的一个框时,无法读取 checkIfPositionIsTaken 函数中未定义的属性“2”。
以下是井字游戏对象的构造函数:
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;
}
};
下面是我创建井字游戏对象的地方:
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;
}
}
});
这是我的第一个问题,如果您需要更多信息,请告诉我。谢谢。
【问题讨论】:
-
row 和 col 都设置为正确的值。将 row 和 col 插入 this.grid 时会抛出错误。
this.grid[row][col]
标签: javascript jquery