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.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";
alert(names);
}
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.