JavaScript enumerator?

You could also try to do something like this:

function Enum(values){
    for( var i = 0; i < values.length; ++i ){
        this[values[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum(["RED","GREEN","BLUE"]);
// check it: alert( config.type.RED );

or even using the arguments parameter, you can do away with the array altogether:

function Enum(){
    for( var i = 0; i < arguments.length; ++i ){
        this[arguments[i]] = i;
    }
    return this;
}
var config = {};
config.type = new Enum("RED","GREEN","BLUE");
// check it: alert( config.type.RED );

Leave a Comment