More About JavaScript Objects
Lesson 7, "Anatomy of an Ajax Application," introduced the building blocks of an Ajax application and discussed how these pieces fit together.
This lesson examines the object at the heart of every Ajax applicationthe XMLHTTPRequest object.
Note
![]() | You briefly met objects in Lesson 4, "Client-Side Coding Using JavaScript," when we discussed the document object associated with a web page. The XMLHTTPRequest object, after it has been created, becomes a further such object within the page's object hierarchy and has its own properties and methods. |
An object can be thought of as a single package containing a set of properties, which contain and classify data, and a set of methods with which the object can perform actions on that data.
Suppose, for example, that we had an object of type wheelbarrow. Such an object might have a property contents, which describes how many items the wheelbarrow holds at any given moment. Methods might include fill(), tip(), forward(), and stop(). When using JavaScript you can design such objects as you see fit.
However, in addition to user-defined objects, JavaScript has a range of ready-made objects for use in scripts. These are referred to as native objects. Examples of JavaScript's native objects include Math(), String(), and Date().
Creating an Instance of an Object
Many objects, such as the document object that you saw in Lesson 4, already exist and therefore do not need you to create an instance of them. Others, however, require you to create an instance of the object in question before you can use it.
You can create an instance of an object by calling a method known as the object's constructor, using the new keyword:
var myBarrow = new Wheelbarrow();
Having created an instance myBarrow of the object wheelbarrow, properties and methods for the object may be manipulated using a simple syntax:
myBarrow.contents = 20;
myBarrow.forward();
myBarrow.stop();
myBarrow.tip();
Of course, you are at liberty to create other instances of the same object and have them exist concurrently:
var myBarrow = new Wheelbarrow();
var yourBarrow = new Wheelbarrow();
myBarrow.contents = 20;
yourBarrow.contents = 50;
The Document Object Model or DOM
We mentioned briefly in Lesson 4 the hierarchy of objects "built in" to a web page and known as the Document Object Model. You access these objects and their properties and methods in the same way as native objects and objects that you devise and create yourself.
Note
![]() | The Document Object Model or DOM is really not a part of JavaScript but a separate entity existing outside it. Although you can use JavaScript to manipulate DOM objects, other scripting languages may equally well access them too. |
In later lessons you'll see how the XMLHTTPRequest object can use XML data returned from the server in response to XMLHTTPRequest calls to create additional DOM objects that you can use in your scripts.