Accessing properties from prototype functions

心已入冬 提交于 2021-02-10 05:43:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8553856/accessing-properties-from-prototype-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!