Thursday, March 24th, 2005
Enums in JavaScript
<>p>Matt Raible pointed me to Ditchnet.org which has some interesting JavaScript tips and tricks.At the top there they discuss enums in JavaScript:
function Suit(name) {
this._name = name;
}
Suit.prototype.toString = function () {
return this._name;
};
Suit.CLUBS = new Suit('clubs');
Suit.DIAMONDS = new Suit('diamonds');
Suit.HEARTS = new Suit('hearts');
Suit.SPADES = new Suit('spades');
It would be a lot nicer to have this in XHR for the status’ for example.
Rather than:
if (xhr.readyState == 4)
you could have:
if (xhr.readyState == XmlHttpRequest.STATUS_READY)
A simple thing, but just gets you away from the ‘hackiness’ factor.
Related Content:











How does this better than constants?
It doesn’t appear to allow you to restrict variables to be only that of what is in your enumerations.
In fact there are no strong types at all in JavaScript, so what would you gain from enumerations. There is no “compile time” at which to catch errors.
Yes, exactly: code clarity. Things like numeric statuses are from a bygone era when we didn’t have the computing power to allow expressiveness in code. No excuse anymore.
I like it but using integers would be more suitable.
Suit.CLUBS = 1;
Suit.DIAMONDS = 2;
Suit.HEARTS = 3;
Suit.SPADES = 4;
At least that way it would be easier to compare them to something other than an object.