在JavaScript中定义枚举的首选语法是什么? [英] What is the preferred syntax for defining enums in JavaScript?

查看:126
本文介绍了在JavaScript中定义枚举的首选语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中定义枚举的首选语法是什么?类似于:

What is the preferred syntax for defining enums in JavaScript? Something like:

my.namespace.ColorEnum = {
    RED : 0,
    GREEN : 1,
    BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
   // whatever
}

还是有更优选的习语?

推荐答案

由于1.8.5可以密封和冻结对象,因此将上面定义为:

Since 1.8.5 it's possible to seal and freeze the object, so define the above as:

var DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})

var DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)

瞧! JS枚举。

但是,这并不能阻止您为变量分配不需要的值,这通常是枚举的主要目标:

However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors

确保更强的类型安全性(使用枚举或其他方式)的一种方法是使用像 TypeScript 流量

One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.

来源

不需要引用但我保持一致性。

Quotes aren't needed but I kept them for consistency.

这篇关于在JavaScript中定义枚举的首选语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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