home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

Chapter 8. Objects

Chapter 3 explained that objects are one of the fundamental data types in JavaScript. They are also one of the most important. This chapter describes JavaScript objects in detail. Basic usage of objects, described in the next section, is straightforward, but as we'll see in later sections, objects have more complex uses and behaviors.

8.1. Objects and Properties

Objects are composite data types: they aggregate multiple values into a single unit and allow us to store and retrieve those values by name. Another way to explain this is to say that an object is an unordered collection of properties, each of which has a name and a value. The named values held by an object may be primitive values like numbers and strings, or they may themselves be objects.

8.1.1. Creating Objects

Objects are created with the new operator. This operator must be followed by the name of a constructor function that serves to initialize the object. For example, we can create an empty object (an object with no properties) like this:

var o = new Object( ); 

JavaScript supports other built-in constructor functions that initialize newly created objects in other, less trivial, ways. For example, the Date( ) constructor initializes an object that represents a date and time:

var now = new Date( );                        // The current date and time
var new_years_eve = new Date(2000, 11, 31);  // Represents December 31, 2000 

Later in this chapter, we'll see that it is possible to define custom constructor methods to initialize newly created objects in any way you desire.

Object literals provide another way to create and initialize new objects. As we saw in Chapter 3, an object literal allows us to embed an object description literally in JavaScript code in much the same way that we embed textual data into JavaScript code as quoted strings. An object literal consists of a comma-separated list of property specifications enclosed within curly braces. Each property specification in an object literal consists of the property name followed by a colon and the property value. For example:

var circle = { x:0, y:0, radius:2 }
var homer = {
              name: "Homer Simpson",
              age: 34,
              married: true,
              occupation: "plant operator",
              email: "homer@simpsons.com"

The object literal syntax is defined by the ECMAScript v3 specification and implemented in JavaScript 1.2 and later.

8.1.2. Setting and Querying Properties

You normally use the . operator to access the value of an object's properties. The value on the left of the . should be a reference to an object (usually just the name of the variable that contains the object reference). The value on the right of the . should be the name of the property. This must be an identifier, not a string or an expression. For example, you would refer to the property p in object o with o.p or to the property radius in the object circle with circle.radius. Object properties work like variables: you can store values in them and read values from them. For example:

// Create an object. Store a reference to it in a variable.
var book = new Object( );

// Set a property in the object.
book.title = "JavaScript: The Definitive Guide"

// Set some more properties. Note the nested objects.
book.chapter1 = new Object( );
book.chapter1.title = "Introduction to JavaScript";
book.chapter1.pages = 19;
book.chapter2 = { title: "Lexical Structure", pages: 6 };

// Read some property values from the object.
alert("Outline: " + book.title + "\n\t" +
      "Chapter 1 " + book.chapter1.title + "\n\t" +
      "Chapter 2 " + book.chapter2.title); 

An important point to notice about this example is that you can create a new property of an object simply by assigning a value to it. Although we declare variables with the var keyword, there is no need (and no way) to do so with object properties. Furthermore, once you have created an object property by assigning a value to it, you can change the value of the property at any time simply by assigning a new value:

book.title = "JavaScript: The Rhino Book" 

8.1.3. Enumerating Properties

The for/in loop discussed in Chapter 6 provides a way to loop through, or enumerate, the properties of an object. This can be useful when debugging scripts or when working with objects that may have arbitrary properties whose names you do not know in advance. The following code shows a function you can use to list the property names of an object:

function DisplayPropertyNames(obj) {
    var names = "";
    for(var name in obj) names += name + "\n";

Note that the for/in loop does not enumerate properties in any specific order, and although it enumerates all user-defined properties, it does not enumerate certain predefined properties or methods.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.