我有一个带有一些属性和原型的构造函数。但是,由于某种原因,我无法访问原型函数中的属性。
下面是一些代码(对代码进行了精简,以便于阅读),只是为了向您展示我的意思。在函数“ renderTiles”中,我可以访问“对”,但是在“ 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...
}
最佳答案
这是因为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。