无法在构造函数中访问属性

时间:2011-12-18 16:49:39

标签: javascript function constructor this

我有一些带有一些属性和原型的构造函数。但是,由于某种原因,我无法访问原型函数的属性。

下面是一些代码(减少代码使其可读)只是为了向您展示我的意思。在函数'renderTiles'中我可以访问'pair',但在'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...
}

1 个答案:

答案 0 :(得分:2)

这是因为this的值取决于您调用turnTiles 的方式。

因为你正在做:

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

... this的值将是prototype对象,但pairs放置在从Game创建的每个单独对象上,而不是{{1} }}

我不知道您是如何调用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]);

或其他什么。

虽然我不知道为什么你在这里使用IIFE,除非你处于循环中。

相关问题