2011-12-18 68 views
1

我有一些構造函數具有一些屬性和原型。但是,由於某種原因,我無法訪問原型函數中的屬性。無法訪問構造函數中的屬性

下面是一些代碼(簡化了代碼,使其可讀),以向您展示我的意思。在'renderTiles'函數中我可以訪問'pairs',但是在'turnTile'中我不能。這是否有明顯的原因,還是不可能通過我的簡化代碼找出?

更新:更新了代碼,使其更清晰......

DESKTOP.Game = function(){ 
    this.pairs = 0; 
} 

DESKTOP.Game.prototype.renderTiles = function() { 

console.log(this.pairs); <- undefined 

var gamearea = $('<div/>', { 
    'text': 'testarea', 
    'class': 'gamearea' 
}).appendTo('.memory:last'); 

alert("this.rows: " + this.rows); 

for (var j = 0; j < this.rows; j++){ 
    var box = document.createElement('div'); 
    for (var i = 0; i < this.cols; i++){ 

     var iterator = (this.cols * j) + i; 

     var img = document.createElement('img'); 
     var aNod = document.createElement('a'); 

     aNod.href = "#"; 
     img.src = "pics/memory/0.png"; 

     aNod.appendChild(img); 
     box.appendChild(aNod); 

     var self = this; 
     (function(place, index) { 
      this.addEventHandler(aNod, 'click', function() { this.turnTile(place, index); return false; }); 
     })(iterator, this.imgArray[iterator]); 
    } 
    gamearea[0].appendChild(box); 
} 
} 

DESKTOP.Game.prototype.turnTile = function(place, id) { 
    console.log(this.pairs); <- undefined 

// removed code... 
} 

回答

2

這是因爲this價值取決於如何你打電話turnTiles

因爲你正在做的:

DESKTOP.Game.prototype.turnTile(place, index) 

...的this值將是prototype對象,但pairs放置從Game創建的每個單獨的對象上,而不是在prototype

我不知道你是怎麼叫renderTiles,但我假設你創建了一個Game的實例並從那裏調用。

不知道你的代碼是如何工作的,我只是猜測你也想在實例上調用addEventHandler

如果是的話,你會替換此:

(function(place, index) { 
    DESKTOP.Game.prototype.addEventHandler(aNod, 'click', function() { DESKTOP.Game.prototype.turnTile(place, index); return false; }); 
})(iterator, this.imgArray[iterator]); 

與此:

var self = this; 
(function(place, index) { 
    self.addEventHandler(aNod, 'click', function() { self.turnTile(place, index); return false; }); 
})(iterator, this.imgArray[iterator]); 

什麼的。

雖然我不確定爲什麼你在這裏使用IIFE,除非你在循環。

+0

感謝您的回答。我嘗試了「var self = this」,但在控制檯中得到以下錯誤消息:「Uncaught TypeError:Object [object DOMWindow] has no method'addEventHandler'」。 – holyredbeard 2011-12-18 17:11:55

+0

我也更新了代碼,使其更加清晰。 – holyredbeard 2011-12-18 17:12:16

+0

@JasonCraig:那是因爲你需要'self.addEventHandler'和'self.turnTile'。你有'this.addEventHandler'和'this.turnTile'。 – RightSaidFred 2011-12-18 17:17:44

相關問題