2011-12-18 94 views
2

我正在重複使用舊的應用程序(遊戲),因此可以運行幾個遊戲。 由於這個原因,我已經將屬性更改爲「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 

} 

...對於其他原型功能也是如此。

+0

你必須顯示調用renderTiles()的代碼。 – jfriend00 2011-12-18 18:39:47

回答

2

您以錯誤的方式致電renderTilesthis將參考Game.prototype而不是gameGame實例)。

與調用它:

this.renderTiles(); 

this指的是什麼函數內部取決於函數是如何被調用。 MDN提供了一個關於這個的good article [MDN]


FWIW:

只要你不直接給Game功能分配的屬性,Game.bricksundefined爲好,沒有關係,你訪問它,以及如何調用該函數。

+0

你說得對。我以錯誤的方式調用函數。增加了var = this,現在我將函數作爲「this.turnTiles()」運行。謝謝! – holyredbeard 2011-12-18 19:41:08