js中定义enum

我们知道Js是弱类型语言,默认也无法定义枚举。我们可以通过自定义的方式实现,基础类如下:

class Enumify {
static closeEnum () {
const enumKeys = []
const enumValues = []
// Traverse the enum entries
for (const [key, value] of Object.entries(this)) {
enumKeys.push(key)
value.enumKey = key
value.enumOrdinal = enumValues.length
enumValues.push(value)
}
// Important: only add more static properties *after* processing the enum entries
this.enumKeys = enumKeys
this.enumValues = enumValues
// TODO: prevent instantiation now. Freeze `this`?
}

/** Use case: parsing enum values */
static enumValueOf (str) {
const index = this.enumKeys.indexOf(str)
if (index >= 0) {
return this.enumValues[index]
}
return undefined
}

static [Symbol.iterator] () {
return this.enumValues[Symbol.iterator]()
}

toString () {
return this.constructor.name + '.' + this.enumKey
}
}

比如我们要定义一个Gender枚举,定义如下:
export class Gender extends Enumify {
static MALE = new Gender(1, '男');
static FEMALE = new Gender(2, '女');
static _ = this.closeEnum();
static getGenderDescribe = (value) => {
if (value === Gender.MALE.getValue()) {
return Gender.MALE.getDescribe()
} else if (value === Gender.FEMALE.getValue()) {
return Gender.FEMALE.getDescribe()
}
return '未知'
}
constructor (value, describe = '') {
super()
this.value = value
this.describe = describe
}

getValue () {
return this.value
}

getDescribe () {
return this.describe
}
}


posted @ 2021-04-20 17:33  天长地久-无为  阅读(6715)  评论(0编辑  收藏  举报