gameI创建了以下" class":
function State(){
this.board = [];
for (i=0; i< 9; i++){
var row = [];
for (j=0; j< 9; j++){
row.push(0);
}
this.board.push(row);
}
}
它有一个名为nextEmptyCell的方法:
State.prototype.nextEmptyCell = function(){
...
}
我创建了这个类的一个实例并将其传递给另一个函数。
game = new State();
function solveSudoku(game){
var next = game.nextEmptyCell();
...
}
在以下行中:var next = game.nextEmptyCell();
我收到错误消息:
&#34;未捕获的TypeError:无法读取属性&#39; nextEmptyCell&#39;未定义&#34;。
我不明白为什么&#39;游戏&#39;未定义以及如何修复此错误。 链接到完整代码:jsfiddle.net/py6kv7ps/5
P.S。有没有更好的方法将JS用作OOP?
答案 0 :(得分:1)
问题来自solveSudoku()
,你是在不传递参数的情况下递归调用的。这就是你得到错误的原因。
&#34;未捕获的TypeError:无法读取属性&#39; nextEmptyCell&#39;的 未定义&#34;
function solveSudoku(game) {
if (solveSudoku(ADD game OBJECT HERE)) {
return game;
}
}
答案 1 :(得分:0)
你可能意味着game.nextEmptyCell()
,而不是state.nextEmptyCell()
。您发布的代码中没有任何名为state
的变量。
答案 2 :(得分:0)
因为你的参数game
会影响同名的glbal变量game
。全局变量game = new State();
具有正确的值。因此,您可以将其传递给方法调用,以便在方法solveSudoku()
function State(){
this.board = [];
for (i=0; i< 9; i++){
var row = [];
for (j=0; j< 9; j++){
row.push(0);
}
this.board.push(row);
}
}
State.prototype.nextEmptyCell = function(){
console.log('egvse gtrs');
document.write('egvse gtrs');
};
var game = new State();
function solveSudoku(game){
var next = game.nextEmptyCell();
}
solveSudoku(game);
&#13;