Since 1.8.5 it's possible to seal and freeze the object, so define the above as:(从1.8.5开始,可以密封和冻结对象,因此将以上定义为:)
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
or(要么)
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
and voila!(和瞧!)
JS enums.(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
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow .(确保类型安全性(使用枚举或其他方式)的程度更高的一种方法是使用诸如TypeScript或Flow之类的工具。)
Source(资源)
Quotes aren't needed but I kept them for consistency.(不需要引号,但为了保持一致性,我保留了它们。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…