Search code examples
javascriptenumsclosuresenumerable

Is this a viable implementation of enums in Javascript?


I was interested in a really quick enumeration of constant values for a project I'm working on, but everything I found on StackOverflow was ridiculously over-complicated if all you want is to store several unchanging values in a single place so that you can reuse them. They also used objects, which meant you could change their values, or you had to understand and use a "freeze" keyword which may not be implemented in your browser.

Is the obvious use of closures here a bad idea? Maybe I'm using them too much, but it seems like they come in handy everywhere. Especially here.

var black = new Color3f(0, 0, 0);
var white = new Color3f(1, 1, 1);
var blue = new Color3f(0, 0, 1);

var Colors = {

    //insert basic stuff for Color3f objects here

    BLACK: function(){
        return black;
    },

    //and so on
};

Solution

  • No need for the extra global variables:

    var Colors = {
    
        //insert basic stuff for Color3f objects here
    
        BLACK: new Color3f(0, 0, 0),
    
        //and so on
    };