The Standard Way ov Defining An Enum
In JavaScript, the standard way to define an enum – according to the TypeScript compiler – is:
"use strict";
var Fruit;
(function (Fruit) {
Fruit[Fruit["BANANA"] = 0] = "BANANA";
Fruit[Fruit["ORANGE"] = 1] = "ORANGE";
Fruit[Fruit["APPLE"] = 2] = "APPLE";
})(Fruit || (Fruit = {}));
Or, if we strip the (unnecessary) mapping from number to string, we can do:
"use strict";
var Fruit = {
"BANANA": 0,
"ORANGE": 1,
"APPLE": 2
};
The Better Way ov Defining An Enum
... However, there is a better way to define an enum – and the method will ensure:
- the enum values are unique,
- the values can't be overriden,
- the definition is hoisted.
var Fruit;
{
Fruit = Object.defineProperties((Fruit = Object.create(null)), {
BANANA: {writable: false, value: Symbol("BANANA")},
ORANGE: {writable: false, value: Symbol("ORANGE")},
APPLE: {writable: false, value: Symbol("APPLE")}
});
}
Top comments (0)