javascriptobjectdefineproperty

declaring javascript object property with a function not working


I'm making a lame text-based game, and I made an object player like so:

var player = {
    displayText: "<span>you</span>",
    currentPosition: 0,
    level: 1,
    health: function() { return 10 + (this.level * 15) },
    strength: function() { return this.level * 5 },
    hitRating: 4
}

My understanding is that you can give an object a function as a property.

However, when I alert(player.health) I get:

function() { return 10 + (this.level * 15) }

What am I doing wrong? Are you not able to declare a object property that way? Is there a way to auto-generate the value of player.health any time it's called later on?


Solution

  • player.health is a function. To call a function, you have to put () after it:

    alert(player.health());