简体   繁体   中英

Passing an object to function. JavaScript

gameI created the following "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);
    }  
}

It has a method called nextEmptyCell:

State.prototype.nextEmptyCell = function(){
  ...
}

I created an instance of this class and passed it to another function.

game = new State();
function solveSudoku(game){
    var next = game.nextEmptyCell();
    ...
} 

On the following line: var next = game.nextEmptyCell(); I receive an error saying:

"Uncaught TypeError: Cannot read property 'nextEmptyCell' of undefined".

I don't understand why 'game' is undefined and how to fix this error. Link to the full code: jsfiddle.net/py6kv7ps/5

PS Is there a better way of using JS as OOP?

Issue comes from solveSudoku() , you are calling it recursively without passing an argument. Thats why you are getting error.

"Uncaught TypeError: Cannot read property 'nextEmptyCell' of undefined".

function solveSudoku(game) {  
      if (solveSudoku(ADD game OBJECT HERE)) {
        return game;
      }
}

You probably meant game.nextEmptyCell() , not state.nextEmptyCell() . There is no variable named state anywhere in the code you posted.

Its because your parameter game shadows the glbal variable game of the same name. The global variable game = new State(); has the correct value. So you can pass it to your method call to use the correct value of game within the method 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM