I am creating a game, in which I declare the object player like so:

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>",
};

however, in player.displayText, this.id is returning undefined, why and what can I do to fix this?

有帮助吗?

解决方案

You don't change the current scope while creating an object literal, so this isn't what you think it is.

Make an object instead:

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');

其他提示

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>",
};

You cannot use "this".. as it is bound to global object (like "window" in browser) .. If you know the name of object use.. objectName.this ..

I have used player.id above to fix the issue.

this is related to function scope, uisng it inside the object decleration wont work. What you can do in this situation is something like 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>";

To get something like this you would need to setup a class as a function. Try this:

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();

Have a look at some Mozilla docs on this here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top