Saturday, July 14, 2007

Objects Are Reference Types


Objects Are Reference Types

All JavaScript data types can be categorized as either primitive or reference types.
These two types correspond to the primitive and composite types discussed in Chapter 3.
Primitive types are the primitive data types: number, string, Boolean, undefined, and null.
These types are primitive in the sense that they are restricted to a set of specific values.
You can think of primitive data as stored directly in the variable itself.
Reference types are objects, including Objects, Arrays, and Functions. Because these types can
hold very large amounts of heterogeneous data, a variable containing a reference type does not
contain its actual value. It contains a reference to a place in memory that contains the actual data.

This distinction will be transparent to you the majority of the time.
But there are some situations when you need to pay particular attention
to the implications of these types. The first is when you create two or
more references to the same object. Consider the following example with primitive types:
var x = 10;
var y = x;
x = 2;
alert("The value of y is: " + y);
This code behaves as you would expect. Because x has a primitive type (number),
the value stored in it (10) is assigned to y on the second line. Changing the value
of x has no effect on y because y received a copy of x’s value. The result is shown here:

Now consider similar code using a reference type:
var x = [10, 9, 8];
var y = x;
x[0] = 2;
alert("The value of y's first element is: " + y[0]);
The result might be surprising:

Because arrays are reference types, the second line copies the reference to x’s data into y.
Now both x and y refer to the same data, so changing the value of this data using either
variable is naturally visible to both x and y.

No comments :