Wednesday, June 22nd, 2005

Anonymous Classes in JavaScript and the XMLHttpRequest API

Category: Articles, JavaScript, XmlHttpRequest

Todd Ditchendorf has written up his thoughts on JavaScript, and API usage.

He discusses the XmlHttpRequest API, and some of its ugliness, and gets into the way popular wrappers of the API work a la:

var client = new BetterHttpClientAPI();
client.addListener({
    id: 123,
	
    responseReceived: function (evt) {
        ....
    },
	
    otherHelperMethod: function() {
        ....
    }
});

JavaScript is a prototype-based OO language, and I find that it is best to NOT try to make it look like a class based one, so the idea of having a JavaScript “object” which has properties, some of which are functions, is a natural way to design an API.

This isn’t exactly anonymous inner classes, as that isn’t the way JavaScript works.

As we see more and more people jump into JavaScript I think we need to do a better job on selling the prototype system, and not try to think of class based languages that we may also use and try to fit JavaScript into that world :)

Posted by Dion Almaer at 9:35 am
4 Comments

+++--
3.3 rating from 12 votes

4 Comments »

Comments feed

If you haven’t read this, it’s a very good read:

http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/

Comment by Jason Carreira — June 22, 2005

What’s the URL of Todd’s comments?

Comment by Ryan — June 22, 2005

The URL is: http://www.ditchnet.org/wp/

Comment by Dion — June 22, 2005

My biggest problem with JavaScript as an prototype based OO language is that it doesn’t give you bound methods and that “sending a message to an object” is the same syntax as “calling an unbound function”. The simplest example of this is:

foo.bar()

is not the same thing as:

var bar = foo.bar;
bar();

is not the same thing as:

[foo.bar][0]();

… and this is absolutely fucking ridiculous if you’re doing callbacks. You need to build up closures with the “intended this”, which has to be named something other than “this” (I usually go for “self”, given Python and Objective-C tendencies).

I usually solve this problem with:
function bind(func, obj) { return function () { return func.apply(obj, arguments); } }

and in constructors you can use that and an iterator to automatically bind everything… however, it’s still extremely stupid that you have to do this at all.

Comment by Bob Ippolito — June 24, 2005

Leave a comment

You must be logged in to post a comment.