Objects

Nothing makes some computer people more miserable than the word object. Fortunately, JavaScript Objects are extremely tame.

What is an object? In general terms, an object is one or more pieces of data and one or more useful functions all collected together into a neat item that can be easily carried around. Usually the data items and the functions are related and work together. Often an object has a particular identity, like 'person', so that it's possible to have many 'person' objects, each one for a different human being. The ability to carry all the stuff about a person or other kind of thing around in one neat item is a very handy and powerful feature of modern computer languages.

Advocates of other programming languages that support objects such as C++, Java, Ada and Eiffel are likely to become enraged by such a simple definition of objects. For those languages, defining and combining objects is a very exact science. However, JavaScript's loosely-typed and interpreted nature is perfectly suited to simple objects, so the definition is a good one in this case.

Here's an example of JavaScript objects:

var thing = new Object;

thing.name  = 'Any old thing';
thing.age   = 59;
thing.hobby = 'moving as little as possible.';

thing.thing2 = new Object;
thing.thing2.name = "thing's own thing";

delete thing;

First, the new operator mentioned earlier creates an Object which is put into thing. thing is still an ordinary variable, it simply contains a new type of value—an Object value. After that's complete, thing is neither undefined nor null. However, Objects initially don't contain much of interest—properties have to be added to them, like ingredients combined to make up a meal. Lines 3 to 5 demonstrate the simple syntax used to add properties:

object-variable-name.property-name = value

Objects can have as many properties as you can find different names for, and each property can contain a value of any type, including another object. Lines 7 and 8 show that the thing Object has a property that is another Object. Finally, Objects can be got rid of, using delete. After delete, thing is null.

An object will also automatically disappear if a function ends and that object was created inside the function and the function doesn't return the object back to its caller. The Disappearing Data chapter has more to say about mechanisms that make objects go away.

© 1997 by Wrox Press. All rights reserved.