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...
}
感謝您的回答。我嘗試了「var self = this」,但在控制檯中得到以下錯誤消息:「Uncaught TypeError:Object [object DOMWindow] has no method'addEventHandler'」。 – holyredbeard 2011-12-18 17:11:55
我也更新了代碼,使其更加清晰。 – holyredbeard 2011-12-18 17:12:16
@JasonCraig:那是因爲你需要'self.addEventHandler'和'self.turnTile'。你有'this.addEventHandler'和'this.turnTile'。 – RightSaidFred 2011-12-18 17:17:44