What is the preferred syntax for defining enums in JavaScript? Something like:
my.namespace.ColorEnum = {
RED : 0,
GREEN : 1,
BLUE : 2
}
// later on
if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}
Or is there a more preferable idiom?
Here's what we all want:
Now you can create your enums:
By doing this, constants can be acessed in the usual way (YesNo.YES, Color.GREEN) and they get a sequential int value (NO = 0, YES = 1; RED = 0, GREEN = 1, BLUE = 2).
You can also add methods, by using Enum.prototype:
Edit - small improvement - now with varargs: (unfortunately it doesn't work properly on IE :S... should stick with previous version then)
It's easy to use, I think. https://stackoverflow.com/a/32245370/4365315
UPDATE:
There is my helper codes(
TypeHelper
).Bottom line: You can't.
You can fake it, but you won't get type safety. Typically this is done by creating a simple dictionary of string values mapped to integer values. For example:
The problem with this approach? You can accidentally redefine your enumerant, or accidentally have duplicate enumerant values. For example:
Edit
Absolutely,
Object.freeze
would totally fix the problem I complained about. I would like to remind everyone that when I wrote the above,Object.freeze
didn't really exist.Now.... now it opens up some very interesting possibilities.
Edit 2
Here's a very good library for creating enums.
http://www.2ality.com/2011/10/enums.html
While it probably doesn't fit every valid use of enums, it goes a very long way.
In ES7 , you can do an elegant ENUM relying on static attributes:
then
The advantage ( of using class instead of literal object) is to have a parent class
Enum
then all your Enums will extends that class.A quick and simple way would be :
I've been playing around with this, as I love my enums. =)
Using
Object.defineProperty
I think I came up with a somewhat viable solution.Here's a jsfiddle: http://jsfiddle.net/ZV4A6/
Using this method.. you should (in theory) be able to call and define enum values for any object, without affecting other attributes of that object.
Because of the attribute
writable:false
this should make it type safe.So you should be able to create a custom object, then call
Enum()
on it. The values assigned start at 0 and increment per item.