ES6 read-only enums that can map value to name

前端 未结 3 633
长情又很酷
长情又很酷 2021-02-07 07:55

I would like to define an enum-like structure in JS, but have two requirements:

  1. The values be read-only, i.e. no users can assign to them.
  2. The values (0, 1
3条回答
  •  时光说笑
    2021-02-07 08:22

    Just recently implemented an Es6 version that works quite well:

    const k_VALUES = {}
    
    export class ErrorCode {
    
        constructor(p_apiCode, p_httpCode){
            this.apiCode = p_apiCode;
            this.httpCode = p_httpCode;
    
            k_VALUES[p_apiCode] = this;
        }
    
    
        static create(p_apiCode){
            if(k_VALUES[p_apiCode]){
                return k_VALUES[p_apiCode];
            }
    
            return ErrorCode.UNKNOWN;
        }
    }
    
    ErrorCode.UNKNOWN                 = new ErrorCode(0,     500);
    ErrorCode.NOT_FOUND               = new ErrorCode(-1000, 404);
    ErrorCode.NOT_FOUND_EMAIL         = new ErrorCode(-1001, 404);
    ErrorCode.BAD_REQUEST             = new ErrorCode(-1010, 404);
    

    I wanted to implement a similar pattern as what we do with Java enums. This enables me to use a constructor to pass values. The constructor then freezes the ErrorCode object - nice and convenient.

    Usage: first import your enum class...

    import {ErrorCode} from "../common/services/errors/ErrorCode";
    

    Now, after importing the enum class, access it like so:

    if( errCode.includes(ErrorCode.BAD_REQUEST.apiCode) ){...}
    

    PS> This is used in conjunction with a Webpack setup using Babel to convert our ES6 classes down for browser compatibility.

提交回复
热议问题