Writing better OO with ATLAS – part IV

Published Wed, Aug 2 2006 12:34

Today I’ll write about enums and flags. Enumerations are used to define a data type which has a set of finite identifiers. When we declare a variable and set it to an enumeration, we’re saying that the variable can only contain one of the values defined by the enumeration list. Flags are very similar to enums; however, with flags we can combine several elements of the list by using the operator bitwise or or bitwise and.

Here’s an example of how to create and use an enumeration:

Type.registerNamespace( "LA" );
Type.createEnum( "LA.SexEnum", "Masc", 0, "Fem", 1 );

var man = LA.SexEnum.Masc;
alert( man );

As we can see, we start by creating an enumeration by using the createEnum method. The method expects to receive several parameters (the 1st is always the name of the enumeration; it is followed by several pairs that define the name and their values).

Flags are created by using the createFlags method:

Type.createFlags( "LA.Hobbies", "Soccer", 1, "Reading", 2, "WatchingTV", 4 );

var hobbies = LA.Hobbies.Soccer | LA.Hobbies.WatchingTV;alert( hobbies );

In this case, I’m creating a new variable and we’re combining two values defined on its enumeration list.

Well, as you might expect, you can also list the values (getValues method), parse the value or convert it to string.

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required)