views:

3977

answers:

4

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?

+14  A: 

This isn't much of an answer, but I'd say that works just fine, personally

Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.

Gareth
+2  A: 

Alerting the name is already possible:

if(currentColor == my.namespace.ColorEnum.RED) {
   // alert name of currentColor (RED: 0)
   var col = my.namespace.ColorEnum;
   for (var name in col) {
     if (col[name] == col.RED)
       alert(name);
   } 

}

Alternatively, you could make the values objects, so you can have the cake and eat it to:

var SIZE = {
  SMALL : {value: 0, name: "Small", code: "S"}, 
  MEDIUM: {value: 1, name: "Medium", code: "M"}, 
  LARGE : {value: 2, name: "Large", code: "L"}
};

var currentSize = SIZE.MEDIUM;
if (currentSize == SIZE.MEDIUM) {
  // this alerts: "1: Medium"
  alert(currentSize.value + ": " + currentSize.name);
}

And btw, if you are interested in namespaces, you may want to have a look at my solution for simple but powerful namespace and dependency management for javascript: Packages JS

Stijn de Witt
+1 I like your alternative a lot!
Blindy
+1  A: 

How to define Enum in JavaScript

var Status =
{

    Failed:0;
    Succeeded:1;

}

function DoAction(status)
{

    switch(Number(status)){

        case Status.Failed:
             // execute some code;
             break;

       case Status.Succeeded:
           //execute some code;
           break;
     }
}
shailesh
A: 

See http://www.codeproject.com/Articles/60661/Visual-Studio-JavaScript-Intellisense-Revisited.aspx

Although the context of the post is Visual Studio intellisense, the enum pattern may make sense. or not. YMMV

Sky Sanders