DCSIMG
Creating Enumeration in JavaScript - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

Creating Enumeration in JavaScript

Enumerations are a great way to make our code much more readable. In a nutshell Enum provides us a way to restrict a variable to one of a fixed set of values. Wouldn't it be nice if we could write one in JavaScript. Well we sure can!

As I wrote in many of my posts earlier each JavaScript object has a property names "prototype" which contains the method/fields of this type. so if we wish to add to a given object a field that acts like an enum we simply need to add it to the prototype too.

Here is a sample that creates a Namespace for defining several enums. In this case 2 enums: Color,FileAccess.

function Enums()
{
   //There is no sence to instansiate enum
   throw Error.notImplemented();
}

Enums.Colors = {Red : 1, Green :2,Yellow :3, Blue : 4}
Enums.FileAccess = {ReadOnly : 1, Write :2,NoAccess :3}

var color = Enums.Colors.Blue;
alert(color);

One thing to note here is that we should use prototypes here since then we will have to create instance in order to user our enums.

Comments

Eric Williams said:

It also might be worth mentioning that this approach allows duplicate values.  If you add an entry to the Enums.Colors collection such as 'Blue : 5' your alert will display 5.  Not that big of a deal you just have to be careful.

# July 18, 2010 1:56 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: