使用ES6在Javascript中枚举 [英] Enums in Javascript with ES6
问题描述
我正在用Javascript重建一个旧的Java项目,并意识到在JS中没有好的方法来创建枚举。
I'm rebuilding an old Java project in Javascript, and realized that there's no good way to do enums in JS.
我能想到的最好的是:
const Colors = {
RED: Symbol("red"),
BLUE: Symbol("blue"),
GREEN: Symbol("green")
};
Object.freeze(Colors);
const
保持颜色
从重新分配,冻结它可以防止变更键和值。我正在使用符号,因此 Colors.RED
不等于 0
,或者除此之外的任何其他内容。
The const
keeps Colors
from being reassigned, and freezing it prevents mutating the keys and values. I'm using Symbols so that Colors.RED
is not equal to 0
, or anything else besides itself.
这个配方有问题吗?还有更好的方法吗?
(我知道这个问题有点重复,但所有的之前的Q / As 都很老了,ES6为我们提供了一些新功能。)
(I know this question is a bit of a repeat, but all the previous Q/As are quite old, and ES6 gives us some new capabilities.)
编辑:
另一个解决方案,它处理序列化问题,但我认为仍有问题:
Another solution, which deals with the serialization problem, but I believe still has realm issues:
const enumValue = (name) => Object.freeze({toString: () => name});
const Colors = Object.freeze({
RED: enumValue("Colors.RED"),
BLUE: enumValue("Colors.BLUE"),
GREEN: enumValue("Colors.GREEN")
});
通过使用对象引用作为值,可以获得与符号相同的冲突避免。
By using object references as the values, you get the same collision-avoidance as Symbols.
推荐答案
这个公式有问题吗?
Is there a problem with this formulation?
我没有看到任何。
有更好的方法吗?
Is there a better way?
我将两个陈述合并为一个:
I'd collapse the two statements into one:
const Colors = Object.freeze({
RED: Symbol("red"),
BLUE: Symbol("blue"),
GREEN: Symbol("green")
});
如果您不喜欢样板文件,例如重复的符号
调用,你当然也可以编写一个辅助函数 makeEnum
,它从名单列表中创建相同的东西。
If you don't like the boilerplate, like the repeated Symbol
calls, you can of course also write a helper function makeEnum
that creates the same thing from a list of names.
这篇关于使用ES6在Javascript中枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!