javascript对象声明不能像我想要的那样工作

时间:2013-09-01 05:34:57

标签: javascript object variable-declaration

我正在创建一个游戏,我在其中声明对象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.displayText中,this.id正在返回undefined,为什么以及我该怎么做才能解决此问题?

4 个答案:

答案 0 :(得分: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');

答案 1 :(得分: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”..因为它绑定到全局对象(如浏览器中的“窗口”)..如果你知道对象的名称使用.. objectName.this ..

我上面使用了player.id来解决问题。

答案 2 :(得分: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 docs on this here.

答案 3 :(得分: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>";