我正在制作一个游戏,将角色的资源存储为包含数据和样式信息的对象
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
}
}
}
要创建称为“能量”的资源,最简单的方法是在角色中的某处添加this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE)
。但是,由于我打算大量使用此模板,所以我想知道是否有一种方法可以自动使资源的_name
属性等于为其分配的角色的属性。
我尝试使用Object.getOwnPropertyNames()
,但按预期,返回的值是添加了属性的之前的值。因为这样做的全部目的是简化资源创建过程,所以我发现稍后发生的一种快速方法是:
this.energy
this.constructResource()
this.health
this.constructResource()
this.mana
this.constructResource()
...etc
其中constructResource
是使用Object.getOwnPropertyNames()
获取最后添加的属性并从此处进行操作的类方法。为了提高可读性(和美学,我必须承认),我将其切换为:
this.energy ; this.constructResource()
this.health ; this.constructResource()
this.mana ; this.constructResource()
...etc
但是,将两个不相关的语句放在一行中感觉就像是代码的味道。这是一个好习惯吗?
如果这太主观而不能问,在将后者的值分配给前者时,是否存在更好的和/或已经标准化的方法来将方法名称隐式传递给方法?
const energyFactory = (min, max, color) => new Resource("energy", min, max, color);
class Character {
constructor() {
this.energy = energyFactory(0, 100, 0xEEEEEE);
}
}
这样,以后如果您对特定属性(例如名称)具有任何其他“静态”值,则可以轻松地将其添加到工厂中,并将其应用于所有energyFactory
调用,而仅在单个位置进行修改。 >