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.