将 属性 名称隐式传递给对象方法的正确方法是什么?
What is the correct way to implicitly pass property names to object methods?
我正在制作一个游戏,我将角色的资源存储为包含数据和样式信息的对象
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
}
}
}
要创建名为 "energy" 的资源,最简单的方法是在我的角色中的某处添加 this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE)
。然而,由于我打算经常使用这个模板,我想知道是否有一种方法可以自动使资源的 _name
属性 等于角色的 属性分配给.
我尝试使用 Object.getOwnPropertyNames()
但正如预期的那样,返回的值是 在 添加 属性 之前的值。由于这样做的全部意义在于简化资源创建过程,因此我发现稍后发生的一种快速方法是:
this.energy
this.constructResource()
this.health
this.constructResource()
this.mana
this.constructResource()
...etc
其中 constructResource
是一个 class 方法,它使用 Object.getOwnPropertyNames()
获取最后添加的 属性 并从那里对其进行操作。为了可读性(和美学,我必须承认)我将其切换为:
this.energy ; this.constructResource()
this.health ; this.constructResource()
this.mana ; this.constructResource()
...etc
但是,将两个不相关的语句放在一行中感觉就像代码的味道。这是一个好习惯吗?
如果这个问题过于主观,是否有更好的 and/or 已经标准化的方法,可以在将后者的值分配给前者时将方法名称隐式传递给方法?
您可以将每个方法包装在另一个具有默认名称参数的方法中
const energyFactory = (min, max, color) => new Resource("energy", min, max, color);
class Character {
constructor() {
this.energy = energyFactory(0, 100, 0xEEEEEE);
}
}
这样,如果您以后有任何其他 "static" 特定 属性 值(如名称),您可以轻松地将其添加到您的工厂中并将其应用于所有 energyFactory
调用,同时只在一个地方修改它。
我正在制作一个游戏,我将角色的资源存储为包含数据和样式信息的对象
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
}
}
}
要创建名为 "energy" 的资源,最简单的方法是在我的角色中的某处添加 this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE)
。然而,由于我打算经常使用这个模板,我想知道是否有一种方法可以自动使资源的 _name
属性 等于角色的 属性分配给.
我尝试使用 Object.getOwnPropertyNames()
但正如预期的那样,返回的值是 在 添加 属性 之前的值。由于这样做的全部意义在于简化资源创建过程,因此我发现稍后发生的一种快速方法是:
this.energy
this.constructResource()
this.health
this.constructResource()
this.mana
this.constructResource()
...etc
其中 constructResource
是一个 class 方法,它使用 Object.getOwnPropertyNames()
获取最后添加的 属性 并从那里对其进行操作。为了可读性(和美学,我必须承认)我将其切换为:
this.energy ; this.constructResource()
this.health ; this.constructResource()
this.mana ; this.constructResource()
...etc
但是,将两个不相关的语句放在一行中感觉就像代码的味道。这是一个好习惯吗?
如果这个问题过于主观,是否有更好的 and/or 已经标准化的方法,可以在将后者的值分配给前者时将方法名称隐式传递给方法?
您可以将每个方法包装在另一个具有默认名称参数的方法中
const energyFactory = (min, max, color) => new Resource("energy", min, max, color);
class Character {
constructor() {
this.energy = energyFactory(0, 100, 0xEEEEEE);
}
}
这样,如果您以后有任何其他 "static" 特定 属性 值(如名称),您可以轻松地将其添加到您的工厂中并将其应用于所有 energyFactory
调用,同时只在一个地方修改它。