jQuery in Action
JavaScript Object fundamentals
323
By the way, there's no need for all the intermediary variables (such as
owner
) we've
created for illustrative purposes in these code fragments. In a short while, we'll
see more efficient and compact ways to declare objects and their properties.
see more efficient and compact ways to declare objects and their properties.
Up to this point, we've referenced properties of an object by using the dot
(period character) operator; but, as it turns out, that's a synonym for a more gen-
eral operator for performing property referencing.
eral operator for performing property referencing.
What if, for example, we have a property named
color.scheme
? Do you notice
the period in the middle of the name? It throws a monkey wrench into the works
because the JavaScript interpreter will try to look up
because the JavaScript interpreter will try to look up
scheme
as a nested property
of
color
.
"Well, just don't do that!" you say. But what about space characters? What about
other characters that could be mistaken for delimiters rather than as part of a
name? And most importantly, what if we don't even know what the property name is
but have it as a value in another variable or as the result of an expression evaluation?
name? And most importantly, what if we don't even know what the property name is
but have it as a value in another variable or as the result of an expression evaluation?
For all these cases the dot operator is inadequate, and we must use the more
general notation for accessing properties. The format of the general property ref-
erence operator is
erence operator is
object[propertyNameExpression]
where propertyNameExpression is a JavaScript expression whose evaluation as a
string forms the name of the property to be referenced. For example, all three of
the following references are equivalent:
string forms the name of the property to be referenced. For example, all three of
the following references are equivalent:
ride.make
ride['make']
ride['m'+'a'+'k'+'e']
as well as
var p = 'make';
ride[p];
Using the general reference operator is the only way to reference properties
whose names don't form valid JavaScript identifiers, such as
whose names don't form valid JavaScript identifiers, such as
ride["a property name that's rather odd!"]
which contains characters not legal for JavaScript identifiers, or whose names are
the values of other variables.
the values of other variables.
Building up objects by creating new instances with the
new
operator and
assigning each property using separate assignment statements can be a tedious
affair. In the next section, we'll look at a more compact and easy-to-read notation
for declaring our objects and their properties.
affair. In the next section, we'll look at a more compact and easy-to-read notation
for declaring our objects and their properties.