我正在创建一个游戏,我在其中声明对象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
,为什么以及我该怎么做才能解决此问题?
答案 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();
答案 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>";