Math chiller
Math chiller

Reputation: 4167

javascript object declaration not working as i want it to

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?

Upvotes: 0

Views: 139

Answers (4)

Tom
Tom

Reputation: 4592

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.

Upvotes: 1

shortspider
shortspider

Reputation: 1055

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

Upvotes: 1

Blender
Blender

Reputation: 298106

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

Upvotes: 2

abipc
abipc

Reputation: 1035

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.

Upvotes: 1

Related Questions