holyredbeard
holyredbeard

Reputation: 21298

Accessing properties from prototype functions

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.

Upvotes: 2

Views: 2326

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

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.

Upvotes: 3

Related Questions