JavaScript - The Definitve Guide - Chapter 9

9.7 Enumerated Types

by Denise Nepraunig

JavaScript

// all examples are taken from JavaScript The Definitive Guide 6th Edition

function enumeration(namesToValues) {

    // a dumm constructor for whatever reason??
    // hm maybe we are a factory stuff
    var enumeration = function() { throw "Can't instantiate enumerations"; };
    
    var proto = enumeration.prototype = {
        constructor: enumeration,
        toString: function() { return this.name; },
        valueOf: function() { return this.value; },
        toJSON: function() { return this.name; }
    };
    
    enumeration.values = [];
    
    for(name in namesToValues) {
        var e = Object.create(proto);
        e.name = name;
        e.value = namesToValues[name];
        enumeration[name] = e;
        enumeration.values.push(e);
    }
    
    enumeration.foreach = function(f,c) {
        for(var i=0; i < this.values.length; i++) {
            f.call(c, this.values[i]);
        }
    };
    
    return enumeration;
}

// now we create a 'coin class'?
var Coin = enumeration({ Penny: 1, Nickel: 5, Dime: 10, Quarter: 25 });
console.log(Coin); // we get an error, because we can't instantiate enumerations
var c = Coin.Dime;
console.log(c);