Java Reference
In-Depth Information
and display the contents of the first element of the array referenced in
mySecondArrayRef
as follows:
alert(mySecondArrayRef[0]);
you'll see it has also magically changed to
100
! However, as you now know, it's not magic; it's
because both variables reference the same array object—when it comes to objects, it's a reference to
the object and not the object itself that is stored in a variable. When you did the assignment, it didn't
make a copy of the array object, it simply copied the reference. Contrast that with the following:
var myVariable = "ABC";
var mySecondVariable = myVariable;
myVariable = "DEF";
alert(mySecondVariable);
In this case you're dealing with a string, which is a primitive data type, as are numbers. This time
the actual values are stored in the variable, so when you do this:
var mySecondVariable = myVariable;
mySecondVariable
gets its own separate copy of the data in
myVariable
. So the alert at the end will
still show
mySecondVariable
as holding
"ABC"
.
To summarize this section, you create JavaScript objects using the following basic syntax:
var myVariable = new ConstructorName(
optional parameters
);
Using an Object's properties
Accessing the values contained in an object's properties is very simple. You write the name of the variable
containing (or referencing) your object, followed by a dot, and then the name of the object's property.
For example, if you defined an
Array
object contained in the variable
myArray
, you could access its
length
property like this:
myArray.length
But what can you do with this property now that you have it? You can use it as you would any other
piece of data and store it in a variable:
var myVariable = myArray.length;
Or you can show it to the user:
alert(myArray.length);
In some cases, you can even change the value of the property, like this:
myArray.length = 12;
However, unlike variables, some properties are read‐only—you can get information from them, but
you can't
change
information inside them.