下面的内容会使对象满足枚举在JavaScript中拥有的所有特征吗?类似于:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
或者我还有别的办法吗?
下面的内容会使对象满足枚举在JavaScript中拥有的所有特征吗?类似于:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
或者我还有别的办法吗?
从1.8.5开始可以达到seal and freeze the object,因此将以上定义为:
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
或
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)
瞧!JS枚举.
但是,这并不妨碍您为变量指定不需要的值,这通常是枚举的主要目标:
let day = DaysEnum.tuesday
day = 298832342 // goes through without any err或s
One way to ensure a stronger degree of type safety (with enums 或 otherwise) is to use a tool like TypeScript 或 Flow.
Quotes aren't needed but I kept them f或 consistency.