samedi 19 octobre 2019

What is the correct way to implicitly pass property names to object methods?

I'm making a game where I store character's resources as objects which contain data and styling information

class Resource {
    constructor(_name, _min, _max, _color){
        this.name = _name
        this.className = "character-" + _name
        this.max = _max
        this.min = _min            
        this.current = _max
        this.color = _color
        }
    }
}

To create a resource called "energy", the simplest way would be to add this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE) somewhere in my character. However, since I plan to use this template a lot, I was wondering if there would be a way to automatically have the _name property of the Resource be equal to the Character's property it's being assigned to.

I tried using Object.getOwnPropertyNames() but as expected, the value returned is the one before the property is added. Since the whole point of this is to simplify the resource creation process, a quick way I found to have it happen later was to do:

this.energy
this.constructResource()
this.health
this.constructResource()
this.mana
this.constructResource()
         ...etc

where constructResource is a class method that uses Object.getOwnPropertyNames() to get the last property added and manipulate it from there. For readability (and aesthetics, I must admit) I switched it to:

 this.energy ; this.constructResource()
 this.health ; this.constructResource()
 this.mana   ; this.constructResource()
         ...etc

However, putting two unrelated statements in a single line feels like a code smell. Is this a good practice?

If that is too subjective to ask, is there a better and/or already standardized way of implicitly passing a method name to a method as you assign the value of the latter to the former?





Aucun commentaire:

Enregistrer un commentaire