Java Reference
In-Depth Information
First you set variable myArrayRef reference to the new array object, and then you set mySecondArrayRef
to the same reference — for example, now mySecondArrayRef is set to reference the same array object.
So when you set the fi rst element of the array to 100, as shown here:
myArrayRef [0] = 100;
and display the contents of the fi rst 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, because 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 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 defi ned 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);
Search WWH ::




Custom Search