'How to use values from another object within the same class for a getter function?
I can't find an answer to what is likely a simple problem: how can I use values from one object to set the values in another object within the same class, using a getter function?
I'm new to JS and can't think of another way to reference the values I need other than using this, but this in this case refers to the object that's calling the getter. I need to reference the other object in the class. I also cannot pass in arguments to a getter function as far as I understand them.
Also, I recognize there are other less dynamic ways of implementing this. My original code just set maxDamage: this.vitals.strength * 2, but then I'd need a method to refresh this variable if vitals.strength changes. I figured that using a getter function might be a more dynamic, concise way of doing this.
In the code below, I'm trying to set attackStats.maxDamage equal to a calculation using vitals.strength such that each time I get the maxDamage the getter returns something like vitals.strength * 2. Also, maxDamage needs to be dynamic because vitals.strength will change often! I'd rather not have to manually refresh it each time this changes.
class Warrior {
vitals = {
maxHealth: 120,
health: 120,
strength: 10,
}
attackStats = {
type: 'Sword Swing',
get maxDamage () {
return [some calculation using vitals.strength]
}
}
I think I could solve the problem by merging the objects into one larger object so that this works as intended, but I want to keep them separate.
How can I pass access vitals.strength from the getter function?
Solution 1:[1]
I don't know what exactly do you ask. But in the class is a constructor missing...
I made an example for you here, maybe it helps to understand how the construction method works.
class Warrior {
constructor ({maxHealth, stregth}) {
this.vitals = {
maxHealth: maxHealth,
health: maxHealth,
strength: stregth,
}
this.attackStats = {
type: 'Sword Swing',
damage: 2,
maxDamage: null,
}
this.setMaxDamage()
}
setMaxDamage () {
this.attackStats.maxDamage = this.vitals.strength * this.attackStats.damage;
}
}
let orcWarrior = new Warrior({maxHealth:120, stregth:10});
console.log(orcWarrior.attackStats.maxDamage);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | exphoenee |
