Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从原型函数访问属性_Javascript_This_Prototype Programming - Fatal编程技术网

Javascript 从原型函数访问属性

Javascript 从原型函数访问属性,javascript,this,prototype-programming,Javascript,This,Prototype Programming,我正在重用一个旧的应用程序(一个游戏),因此可以一次运行几个游戏。 由于这个原因,我将属性更改为“this.propery”,这在我的应用程序中随处可见。 但是,唯一可以访问属性的原型函数是“startGame”。 我已经尝试过“this.bricks”和“Game.bricks”,但在尝试使用“startGame”的任何其他函数访问它们时,这两个函数都没有定义 有给我的建议吗 var game = new Game(); game.startGame(); Game = function()

我正在重用一个旧的应用程序(一个游戏),因此可以一次运行几个游戏。 由于这个原因,我将属性更改为“this.propery”,这在我的应用程序中随处可见。 但是,唯一可以访问属性的原型函数是“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

}
var game=新游戏();
game.startGame();
游戏=功能(){
这1.2=2;
此值为0.checkOdd偶数;
...
}
Game.prototype.startGame=函数(){

console.log(this.bricks)您以错误的方式调用了
renderTiles
将引用
Game.prototype
而不是
Game
(游戏
实例)

称之为:

this.renderTiles();
在函数中所指的内容取决于函数的调用方式。MDN提供了一个关于这一点的示例


FWIW:


只要不直接将属性分配给
Game
函数,
Game.bricks
也应该是
未定义的
,无论您在何处访问它以及如何调用函数。

您必须显示调用renderTiles()的代码.你是对的。我用错误的方式调用函数。添加了var that=this,现在我以“this.turnTiles()”的形式运行函数。谢谢!