Enums in Javascript with ES6

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

    Is there a problem with this formulation?

    I don't see any.

    Is there a better way?

    I'd collapse the two statements into one:

    const Colors = Object.freeze({
        RED:   Symbol("red"),
        BLUE:  Symbol("blue"),
        GREEN: Symbol("green")
    });
    

    If you don't like the boilerplate, like the repeated Symbol calls, you can of course also write a helper function makeEnum that creates the same thing from a list of names.

提交回复
热议问题