Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top