ℙℕℤℝ 2008-11-13 19:09
浏览 620
已采纳

在 JavaScript 中定义 enums 的首选语法是什么?

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
}

Or is there a more preferable idiom?

转载于:https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript

  • 写回答

30条回答 默认 最新

  • ~Onlooker 2011-02-18 11:03
    关注

    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, ...})
    

    or

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

    and voila! JS enums.

    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
    

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

    Source

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大