我正在重复使用旧的应用程序(游戏),因此可以同时运行多个游戏。 因此,我已将属性更改为“this.propery”,它在我的应用程序中随处使用。 然而,唯一可以访问属性的原型(prototype)函数是“startGame”。 我已经尝试过“this.bricks”和“Game.bricks”,但是当尝试在“startGame”的任何其他函数中访问它们时,两者都是未定义的。
有什么建议可以给我吗?
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
}
...其他原型(prototype)函数也是如此。
最佳答案
您以错误的方式调用renderTiles
。 this
将引用 Game.prototype
而不是 game
(Game
实例)。
调用它:
this.renderTiles();
this
在函数内部指的是什么取决于函数的调用方式。 MDN 提供了 good article [MDN]关于这一点。
FWIW:
只要您不直接将属性分配给 Game
函数,Game.bricks
也应该是 undefined
,无论在哪里您访问它以及如何调用该函数。
关于javascript - 从原型(prototype)函数访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8553856/