Enums in Javascript with ES6

前端 未结 15 1899
青春惊慌失措
青春惊慌失措 2020-12-12 10:42

I\'m rebuilding an old Java project in Javascript, and realized that there\'s no good way to do enums in JS.

The best I can come up with is:

const C         


        
15条回答
  •  半阙折子戏
    2020-12-12 11:33

    Here is my approach, including some helper methods

    export default class Enum {
    
        constructor(name){
            this.name = name;
        }
    
        static get values(){
            return Object.values(this);
        }
    
        static forName(name){
            for(var enumValue of this.values){
                if(enumValue.name === name){
                    return enumValue;
                }
            }
            throw new Error('Unknown value "' + name + '"');
        }
    
        toString(){
            return this.name;
        }
    }
    

    -

    import Enum from './enum.js';
    
    export default class ColumnType extends Enum {  
    
        constructor(name, clazz){
            super(name);        
            this.associatedClass = clazz;
        }
    }
    
    ColumnType.Integer = new ColumnType('Integer', Number);
    ColumnType.Double = new ColumnType('Double', Number);
    ColumnType.String = new ColumnType('String', String);
    

提交回复
热议问题