gpt4 book ai didi

javascript - 将属性名称隐式传递给对象方法的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-28 03:27:51 24 4
gpt4 key购买 nike

我正在制作一个游戏,将 Angular 色的资源存储为包含数据和样式信息的对象

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”的资源,最简单的方法是在我的 Angular 色中的某处添加 this.energy = CharacterResource("energy", 0, 100, 0xEEEEEE)。但是,由于我计划经常使用此模板,因此我想知道是否有一种方法可以自动使资源的 _name 属性等于它所分配到的 Angular 色的属性。

我尝试使用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 调用,同时仅修改它在一个地方。

关于javascript - 将属性名称隐式传递给对象方法的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com