Enums in Javascript with ES6

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

    Update 11.05.2020:
    Modified to include static fields and methods to closer replicate "true" enum behavior.

    If you're planning on updating I would recommend trying to use what I call an "Enum Class" (barring any browser or runtime env limitations you can't accept). It's basically a very simple and clean class that uses private fields and limited accessors to simulate the behavior of an enum. This is something I sometimes do in C# when I want to build more functionality into an enum.

    I realize private class fields are still experimental at this point but it seems to work for the purposes of creating a class with immutable fields/properties. Browser support is decent as well. The only "major" browsers that don't support it are Firefox (which I'm sure they will soon) and IE (who cares).

    DISCLAIMER:
    I am not a developer. I just put this together to solve the limitations of nonexistent enums in JS when I was working on a personal project.

    Sample Class

    class Colors {
        // Private Fields
        static #_RED = 0;
        static #_GREEN = 1;
        static #_BLUE = 2;
    
        // Accessors for "get" functions only (no "set" functions)
        static get RED() { return this.#_RED; }
        static get GREEN() { return this.#_GREEN; }
        static get BLUE() { return this.#_BLUE; }
    }
    

    You should now be able to call your enums directly.

    Colors.RED; // 0
    Colors.GREEN; // 1
    Colors.BLUE; // 2
    

    The combination of using private fields and limited accessors means that the existing enum values are well protected (they're essentially constants now).

    Colors.RED = 10 // Colors.RED is still 0
    Colors._RED = 10 // Colors.RED is still 0
    Colors.#_RED = 10 // Colors.RED is still 0
    

提交回复
热议问题