Monday, April 21, 2008

JavaScript enums

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/javascript_enums.htm]

While JavaScript does not explicitly have the enum keyword, you can work around it using JS rich objects to get the functional equivalent. Here's a minimalist example that defines the enum, passes it in as a parameter, and then checks for it in a switch-case statement. Although, this doesn't throw a "compile time" exception if you pass in an invalid value.

    var Enum_Colors =
    {
      Red:0,
      Blue:1,
      Green:2,
      Yellow:3
    };

   
    function DoStuff()
    {
      TestEnum(Enum_Colors.Green);
    }

    function DoError()
    {
      TestEnum(Enum_Colors.Unknown); //Bad
    }
    function TestEnum(objColorEnum)
    {
      var str;
      switch(objColorEnum)
      {
        case Enum_Colors.Red:
          str = "red";
          break;
        case Enum_Colors.Blue:
          str = "blue";
          break;
        case Enum_Colors.Green:
          str = "green";
          break;
        case Enum_Colors.Yellow:
          str = "yellow";
          break;
        default:
          str = "none";
          break;
      }
     
      alert("The enum passed in is: " + str);
    }

 Thanks to VS2008, you at least get JS intellisence on the "Enum_Colors" object, so that's better than just typing in error-prone literal strings.

No comments:

Post a Comment