Thursday, March 24th, 2005

Enums in JavaScript

Category: Ajax, 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:

  • Junk JavaScript?
    Should JavaScript and HTML be replaced with "proper" languages that might give more bang for the buck in rich Internet applications (RIAs)? One reader...
  • Refresh Using Java Script
    +++--
    3.7 rating from 12 votes

3 Comments »

Comments feed

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.

Comment by Steve Currency — March 24, 2005

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.

Comment by cmg — April 4, 2005

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.

Comment by Fluxtah — November 14, 2006

Leave a comment

You must be logged in to post a comment.