Enums in Javascript with ES6

前端 未结 15 1868
青春惊慌失措
青春惊慌失措 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:42

    If you don't need pure ES6 and can use Typescript, it has a nice enum:

    https://www.typescriptlang.org/docs/handbook/enums.html

    0 讨论(0)
  • 2020-12-12 11:45

    Maybe this solution ? :)

    function createEnum (array) {
      return Object.freeze(array
        .reduce((obj, item) => {
          if (typeof item === 'string') {
            obj[item.toUpperCase()] = Symbol(item)
          }
          return obj
        }, {}))
    }
    

    Example:

    createEnum(['red', 'green', 'blue']);
    
    > {RED: Symbol(red), GREEN: Symbol(green), BLUE: Symbol(blue)}
    
    0 讨论(0)
  • 2020-12-12 11:46

    This is my personal approach.

    class ColorType {
        static get RED () {
            return "red";
        }
    
        static get GREEN () {
            return "green";
        }
    
        static get BLUE () {
            return "blue";
        }
    }
    
    // Use case.
    const color = Color.create(ColorType.RED);
    
    0 讨论(0)
提交回复
热议问题