Objects

An object is a collection of named values. These named values are usually referred to as properties of the object. (Sometimes they are called fields of the object, but this usage can be confusing.) To refer to a property of an object, you refer to the object, followed by a period and the name of the property. For example, if an object named image has properties named width and height, we can refer to those properties like this:

image.width
image.height

Properties of objects are, in many ways, just like JavaScript variables; they can contain any type of data, including arrays, functions, and other objects. Thus, you might see JavaScript code like this:

document.myform.button

This code refers to the button property of an object that is itself stored in the myform property of an object named document.

As mentioned earlier, when a function value is stored in a property of an object, that function is often called a method, and the property name becomes the method name. To invoke a method of an object, use the . syntax to extract the function value from the object, and then use the ( ) syntax to invoke that function. For example, to invoke the write( ) method of the Document object, you can use code like this:

document.write("this is a test");

Objects in JavaScript have the ability to serve as associative arrays -- that is, they can associate arbitrary data values with arbitrary strings. When an object is used in this way, a different syntax is generally required to access ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.