Section 7.1. Creating Objects


7.1. Creating Objects

Objects are composite datatypes: they aggregate multiple values into a single unit and allow you 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, such as numbers and strings, or they may themselves be objects.

The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces. Each property name can be a JavaScript identifier or a string, and each property value can be a constant or any JavaScript expression. Here are some examples:

 var empty = {};  // An object with no properties var point = { x:0, y:0 }; var circle = { x:point.x, y:point.y+1, radius:2 }; var homer = {     "name": "Homer Simpson",     "age": 34,     "married": true,     "occupation": "plant operator",     'email': "homer@example.com" }; 

An object literal is an expression that creates and initializes a new and distinct object each time it is evaluated. That is, a single object literal can create many new objects if it appears within the body of a loop in a function that is called repeatedly.

The new operator can create specialized kinds of objects. You follow it with an invocation of a constructor function that initializes the properties of the object. For example:

 var a = new Array(); // Create an empty array var d = new Date();  // Create an object representing the current date and time var r = new RegExp("javascript", "i");  // Create a pattern-matching object 

The Array(), Date(), and RegExp() constructors shown above are a built-in part of core JavaScript. (The Array() constructor is described later in this chapter, and you can look up the others in Part III.) The Object() constructor creates an empty object, just as the literal {} does.

It is also possible to define your own constructor functions in order to initialize newly created objects in whatever way you'd like. You'll learn how to do this in Chapter 9.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net