Creating an enum

Creation of Enum-types is done using the Enum function and can be done in multiple ways.

Plain object

As shown in the example in the introduction, an enum can be created using a plain object:

var Weekdays = Enum('Weekdays', {
    SUNDAY: 0,
    MONDAY: 1,
    // ...
});

From an existing class

An Enum-type can also be created using an already existing class definition. When a class definition is passed as the second argument instead of an object, all constants from the class are used. This works for interfaces as well.

var Compass = Class({
    'const NORTH' : 'north',
    'const SOUTH' : 'south'
    // ...
});

var Direction = Enum('Direction', Compass);

console.log(Direction.NORTH); // "north"

An Enum is unique and can only be created once. Attempting to create an Enum that already exists under the same name results in an error.

Inside an existing class

It is possible to create an Enum from an existing class without the use of the Enum function. To achieve this, use the enum parameter in the class definition and give it a name.

The name of the enumerator cannot be the same as the class because it would be ambiguous when validating an instance of a specific class type versus an enum type.

var Compass = Class({ enum: 'Direction', expose_enum: true }, {
    'const NORTH' : 'north',
    'const SOUTH' : 'south'
    // ...
});

// If expose_enum is true, Direction is now exposed as a global variable.
console.log(Direction.NORTH); // North

Exposing an Enum can only be done when nothing of the same name already exists in the global namespace. For example, naming the Enum "Class" and exposing it will result in an error.