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
    }
    }


  • 相关阅读:
    不要对春运抱有幻想
    初识HTTP消息头(一)
    java中ArrayList 、LinkList区别以及速度对比
    jar包和war包的区别
    LUA 日期处理
    NGINXLUA——变量浅谈
    JDK和JRE的区别
    理解HTTP消息头 (五)——使用multipart/formdata上传文件
    安装Jetty
    TOMCATJARWAR事例讲解
  • 原文地址:https://www.cnblogs.com/jianglijs/p/14682059.html
Copyright © 2011-2022 走看看