(picture)

March 12, 2003

JavaScript objects

Well. Isn't JavaScript just so unfashionable? It's slow, has a lazy garbage collector (too lazy for some of the strict-lifetime COM work we'd like to do), and there are a few really bad pitfalls in the syntax (for example, not requiring semicolons at the end of a statement).

But still, it's incredible. Here's a start at saying why.

Object == hashtable

So, the first (and probably the most important) thing is: everything (approximately) derives from "Object", and an Object is a hashtable. That is, a container for named values. Anytime you like, you can add new members into the hashtable.

Arrays are hashtables. Functions are hashtables. Strings are hashtables. Numbers are hashtables. And so on.

These pairs of statements are identical:

var a = new Object();
var a = {};

You can construct a whole hashtable at once with curly-braces and colons:

var a = { "Name" : value, "Thing" : somethingElse };

Secondly, the "dot" notation is the same thing as a hashtable lookup. There's another syntax for that: square brackets. So these are the same:

a["Thing"] = somethingElse;
a.Thing = somethingElse;

There's also a kinda-hidden "global object". If you're at the main path of a program, outside all the functions, you can usually get to it with "this". Everything you declare at global scope -- global functions, global variables, and so on -- ends up as a property on the global object. Which is a hashtable, of course.

Wild, huh?