Java Reference
In-Depth Information
Creating an Object
You have already seen an example of an Array object being created. To create an Array object, you used
the following JavaScript statement:
var myArray = new Array();
So how is this statement made up?
The fi rst half of the statement is familiar to you. You use the var keyword to defi ne a variable called
myArray. This variable is initialized, using the equals sign assignment operator (=), to the right-hand
side of the statement.
The right-hand side of the statement consists of two parts. First you have the operator new. This tells
JavaScript that you want to create a new object. Next you have Array(). This is the constructor for an
Array object. It tells JavaScript what type of object you want to create. Most objects have constructors
like this. For example, the Date object has the Date() constructor. The only exception you see in this
topic is the Math object, and this will be explained in a later part of the chapter.
You also saw in Chapter 2 that you can pass parameters to the constructor Array() to add data to your
object. For example, the following code creates an Array object that has three elements containing the
data “Paul”, “Jeremy”, and “Nick”:
var myArray = new Array(“Paul”, “Jeremy”, “Nick”);
Let's see some more examples, this time creating a Date object. The simplest way to do so is like this:
var myDate = new Date();
This will create a Date object containing the date and time when it was created. However, the following
line creates a Date object containing the date 1 January 2010:
var myDate = new Date(“1 Jan 2010”);
How object data are stored in variables differs from how primitive data, such as text and numbers, are
stored. (Primitive data are the most basic data possible in JavaScript.) With primitive data, the variable
holds the data's actual value. For example:
var myNumber = 23;
This code means that the variable myNumber holds the data 23. However, variables assigned to objects
don't hold the actual data, but rather a reference to the memory address where the data can be found.
This doesn't mean you can get hold of the memory address — this is something only JavaScript has
details of and keeps to itself in the background. All you need to remember is that when you say that a
variable references an object, you mean it references a memory address. This is shown in the following
example:
var myArrayRef = new Array(0, 1, 2);
var mySecondArrayRef = myArrayRef;
myArrayRef[0] = 100;
alert(mySecondArrayRef[0]);
Search WWH ::




Custom Search