Enums in Javascript with ES6

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

    Here is an Enum factory that avoids realm issues by using a namespace and Symbol.for:

    const Enum = (n, ...v) => Object.freeze(v.reduce((o, v) => (o[v] = Symbol.for(`${n}.${v}`), o), {}));
    
    const COLOR = Enum("ACME.Color", "Blue", "Red");
    console.log(COLOR.Red.toString());
    console.log(COLOR.Red === Symbol.for("ACME.Color.Red"));

提交回复
热议问题