3

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?

Jan Turoň
  • 29,041
  • 21
  • 114
  • 159
Math chiller
  • 4,078
  • 6
  • 25
  • 42

3 Answers3

11

If you want to create property with accessor on JS object, proper way to do this is to use Object.defineProperty.

In your case:

// original object
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
}

// create property with accessor method
Object.defineProperty(player, "health", {
    get: function () {
        return 10 + (player.level * 15)
    }
})

// call the property
alert(player.health);  // 25
player.level++;
alert(player.health);  // 40
royhowie
  • 10,805
  • 14
  • 48
  • 67
Jan Turoň
  • 29,041
  • 21
  • 114
  • 159
10

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

alert(player.health());
Barmar
  • 669,327
  • 51
  • 454
  • 560
4

You need to call the function, player.health()

Cole Pilegard
  • 562
  • 2
  • 10