使用 ES6 在 JavaScript 中枚举 [英] Enums in Javascript with ES6

查看:58
本文介绍了使用 ES6 在 JavaScript 中枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 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 被重新分配,冻结它可以防止改变键和值.我正在使用符号,以便 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.

这个公式有问题吗?有没有更好的方法?

(我知道这个问题有点重复,但所有之前的问答都是相当古老,而 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?

我什么都没看到.

有更好的方法吗?

我会将两个语句合二为一:

I'd collapse the two statements into one:

const Colors = Object.freeze({
    RED:   Symbol("red"),
    BLUE:  Symbol("blue"),
    GREEN: Symbol("green")
});

如果您不喜欢样板文件,例如重复的 Symbol 调用,您当然也可以编写一个辅助函数 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆