I have a constructor function with some properties and prototypes. However, by some reason I can’t access the properties in on of the prototype functions.
Below is some code (reduced the code so it’s readable) just to show you what I mean. In the function ‘renderTiles’ I can access ‘pairs’, but in ‘turnTile’ I can’t. Is there an obvious reason for this or is it impossible to find out with through my reduced code?
UPDATE: Updated the code to make it more clear…
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...
}
It’s because the value of
thisdepends on how you callturnTiles.Because you’re doing:
…the value of
thiswill be theprototypeobject, butpairsis placed on each individual object created fromGame, not on theprototype.I have no idea how you’re calling
renderTiles, but I’d assume that you created an instance ofGameand called from there.Not knowing how your code works, I’d just guess that you want
addEventHandlerto be called on the instance as well.If so, you’d replace this:
with this:
or something.
Though I’m not sure why you’re using an IIFE here unless you’re in a loop.