zoukankan      html  css  js  c++  java
  • 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
    }
    }


  • 相关阅读:
    常用正则表达式实例
    java doc注释
    不让WINDOWS检测硬盘的方法
    maven eclipse插件使用问题解决
    indexof 和 indexofany有什么区别
    asp.net验证码
    C#里如何把数据库里的日期显示为只包含年月日
    雷人的发现 谷歌浏览器三大不为人知的秘密
    三层架构实例
    正则表达式30分钟入门教程
  • 原文地址:https://www.cnblogs.com/jianglijs/p/14682059.html
Copyright © 2011-2022 走看看