Preliminary documentation for Ice 3.7.1 Beta. Do not use in production applications. Refer to the space directory for other releases.

JavaScript does not have an enumerated type, so a Slice enumeration is emulated using JavaScript objects where each enumerator is an instance of the same type. For example:

Slice
enum Fruit { Apple, Pear, Orange }

The generated JavaScript code is equivalent to the following:

JavaScript
class Fruit { ... }
Fruit.Apple = new Fruit("Apple", 0);
Fruit.Pear = new Fruit("Pear", 1);
Fruit.Orange = new Fruit("Orange", 2);

Each enumerator defines name and value properties that supply the enumerator's name and ordinal value, respectively. Enumerators also define hashCodeequals and toString methods, and the enumerated type itself defines a valueOf method that converts ordinal values into their corresponding enumerators.

Suppose we modify the Slice definition to include a custom enumerator value:

Slice
enum Fruit { Apple, Pear = 3, Orange }

The generated code changes accordingly:

JavaScript
class Fruit = { ... };
Fruit.Apple = new Fruit("Apple", 0);
Fruit.Pear = new Fruit("Pear", 3);
Fruit.Orange = new Fruit("Orange", 4);

Given the above definitions, we can use enumerated values as follows:

JavaScript
let f1 = Fruit.Apple;
let f2 = Fruit.Orange;

if(f1 === Fruit.Apple)   // Compare with constant
{
    // ...
}

if(f1 === f2)            // Compare two enums
{
    // ...
}

switch(f2)               // Switch on enum
{
    case Fruit.Apple:
        // ...
        break;
    case Fruit.Pear:
        // ...
        break;
    case Fruit.Orange:
        // ...
        break;
}
 
let f = Fruit.valueOf(3); // Convert an ordinal value to its enumerator, or undefined if no match
console.log(f.name + " = " + f.value); // Outputs "Pear = 3"

Note that the generated type may contain other members, which we have not shown. These members are internal to the Ice run time and you must not use them in your application code (because they may change from release to release).

See Also

  • No labels