2

I'm reusing an old application (a game) so it's possible to run several games at ones. By that reason I've changed the properties to "this.propery", which are used everywhere in my application. However, the only prototype function that can access the properties is "startGame". I have tried both "this.bricks" and "Game.bricks", but both are undefined when trying to reach them in any other function that "startGame".

Any tips for me?

var game = new Game();
game.startGame();

Game = function(){
this.bricks = 2;
this.checkOddEven = 0;
    ...
}


Game.prototype.startGame = function() {
    console.log(this.bricks) <- 2
    console.log(Game.bricks) <- 2

// Code goes here...

    Game.prototype.renderTiles()
}

Game.prototype.renderTiles = function() {

// code goes here...

    console.log(this.bricks) <- undefined
    console.log(Game.bricks) <- undefined

}

... the same goes for the other prototype functions.

Rob W
  • 341,306
  • 83
  • 791
  • 678
holyredbeard
  • 19,619
  • 32
  • 105
  • 171

1 Answers1

3

You are calling renderTiles in the wrong way. this will refer to Game.prototype instead of game (the Game instance).

Call it with:

this.renderTiles();

What this refers to inside a function depends on how the function is called. MDN provides a good article [MDN] about that.


FWIW:

As long as you are not assigning properties directly to the Game function, Game.bricks should be undefined as well, not matter where you access it and how you call the function.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • You were right. I was calling the functions in wrong way. Added var that = this and now i run the functions as "this.turnTiles()". Thanks! – holyredbeard Dec 18 '11 at 19:41