tags:

views:

1310

answers:

2

Hi,

how can I create an enumeration in javascript?

+9  A: 

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:

var DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}

Document.Write("Enumerant: " + DaysEnum.tuesday);

The problem with this approach? You can accidentally redefine your enumerant, or accidentally have duplicate enumerant values. For example:

DaysEnum.monday = 4; // whoops, monday is now thursday, too
Randolpho
there is type safety in javascript ?
Scott Evernden
So don't map values to object properties. Use getter to access enumerant (stored as a property of, say, "private" object). A naive implementation would look like - `var daysEnum = (function(){ var daysEnum = { monday: 1, tuesday: 2 }; return { get: function(value){ return daysEnum[value]; } } })(); daysEnum.get('monday'); // 1`
kangax
@Scott Evernden: point taken. @kangax: the point is that it's still a hack. Enums simply don't exist in Javascript, period, end of story. Even the pattern suggested by Tim Sylvester is still a less than ideal hack.
Randolpho
+1  A: 

This is the best solution I've found:

http://www.ditchnet.org/wp/2005/03/21/typesafe-enum-pattern-in-javascript/

Tim Sylvester