0

I am very new to JS.

I am trying to define properties of a variable, but the trick is that I want JS to define a new variable while defining another.

This does not work:

var robber = {
        health: 10,
        halfHealth: this.health/2,
};

I expect robber.halfHealth to be 5, but answer is NaN. I guess it does it because var robber is not really defined by the time attempt to calculate halfHealth is done?

If I put it an another way it works:

var robber = {
        health: 10,
        // halfHealth: this.health/2,
};

var robberHalfHealth = robber.health/2;

I do not want to have hundreds of variables, but want all variables related to "robber" to live {in one house}, so to say.

P.S. One of ways might be to add function which would define halfHealth and do robber.init(), but is there a more straightforward solution?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Vadimster
  • 119
  • 9
  • Instead of declaring a second variable in your second version, you can say `robber.halfHealth = robber.health / 2;` to add a second property to the `robber` after creating it. – nnnnnn Nov 06 '14 at 13:38

1 Answers1

1

Why not use a function?

var robber = { health: 10, halfHealth: function(){return this.health/2;} }
robber.halfHealth(); // 5
AlexanderBrevig
  • 1,967
  • 12
  • 17
  • 1
    Note that this doesn't have the same result in that the function will always return half of whatever the current value of `health` is. If the idea is to be able to tell whether a changeable `health` has dropped below half of its original value this won't work. – nnnnnn Nov 06 '14 at 13:40
  • This is true, though, if checking for this is a requirement - I would use a function for that too, then name health => originalHealth/maxHealth and have another property for storing current health – AlexanderBrevig Nov 06 '14 at 13:48