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
};

Answers


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
};

Objects can't create closure in JavaScript because they never create variable scope.

To use closure, you'd do something like this.

var color = (function() {

    var color_map = {
        black: new Color3f(0, 0, 0),
        white: new Color3f(1, 1, 1),
        blue: new Color3f(0, 0, 1)
    };

    return function(c) { return color_map[c.toLowerCase()]; };
})();

Then invoke the color function to fetch a color.

color("black");

Take note that the outer function is invoked immediately, and the inner function is the one that is assigned to the color variable.

Also, you may want to wrap all your code in another function to prevent any sort of modification.

(function() {
    var color = (function() {
        var color_map = {
            black: new Color3f(0, 0, 0),
            white: new Color3f(1, 1, 1),
            blue: new Color3f(0, 0, 1)
        };

        return function(c) { return color_map[c.toLowerCase()]; };
    })();

    // the rest of your code
    alert(color("black"));
})();

Need Your Help

CollapsiblePanelExtender doesn't open up all the way on initial page load

asp.net .net-2.0 ajaxcontroltoolkit collapsiblepanelextender

I'm using CollapsiblePanelExtender from AjaxControlToolkit, it works fine when i click on it, but it won't expand all the way on the initial page load (expands about 90%).

Cocoa, output current App path

osx cocoa xcode4

I am working on OS X application. In the code, I would like to output a path of the current Mac OS App to a variable for future use. So later I could read the files in the same folder. Could anyon...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.