1

我正在创建一个游戏,我在其中声明对象player,如下所示:

var player = {
    "id": "player",
    "displayText" : "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
    "class='onTop' id='" + this.id + "' alt='you' border='0' />" + 
    "<div id = '" + this.id + "health' class = 'healthLost hide'></div>",
};

但是,在player.displayTextthis.id正在返回undefined,为什么以及我能做些什么来解决这个问题?

4

4 回答 4

2

在创建对象字面量时,您不会更改当前范围,所以this不是您认为的那样。

改为创建一个对象:

function Player(id) {
    this.id = id;
    this.displayText = "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
        "class='onTop' id='" + this.id + "' alt='you' border='0' />" +
        "<div id = '" + this.id + "health' class = 'healthLost hide'></div>";
}

var p = new Player('foo');
于 2013-09-01T05:50:11.047 回答
1
var player = {
    "id": "player",
    "displayText" : "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
    "class='onTop' id='" + player.id + "' alt='you' border='0' />" + 
    "<div id = '" + player.id + "health' class = 'healthLost hide'></div>",
};

您不能使用“this”.. 因为它绑定到全局对象(如浏览器中的“window”).. 如果您知道对象的名称,请使用.. objectName.this ..

我已经使用上面的 player.id 来解决这个问题。

于 2013-09-01T05:49:50.170 回答
1

要获得这样的东西,您需要将类设置为函数。试试这个:

var player_class = function(){
    this.id = "player"
    this.displayText = "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'" +
    "class='onTop' id='" + this.id + "' alt='you' border='0' />" + 
    "<div id = '" + this.id + "health' class = 'healthLost hide'></div>";
}

var player = new player_class();

在这里查看一些Mozilla 文档。

于 2013-09-01T05:49:55.140 回答
1

this与函数范围有关,在对象声明中使用它是行不通的。在这种情况下你可以做的是这样的:

var player = {
"id": "player",
"displayText" : "<img src = 'http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png'"
};
player.displayText += "class='onTop' id='" + player.id + "' alt='you' border='0' /><div id = '" + player.id + "health' class = 'healthLost hide'></div>";
于 2013-09-01T05:51:00.767 回答