Java Reference
In-Depth Information
In this section, you look at how to go about creating an object and, having done that, how you use
its properties and methods.
Creating an Object
To create many types of objects, you use the
new
operator. The following statement creates a
Date
object:
var myDate = new Date();
The first half of the statement is familiar to you. You use the
var
keyword to define a variable called
myDate
. 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
Date()
. This is the
constructor
for a
Date
object. It's a function that tells JavaScript what type of object you want to create. Most
objects have constructors like this. For example, the
Array
object has the
Array()
constructor (but
remember, we typically don't use it in favor of the literal
[]
). The only exception you see in this topic
is the
Math
object, and this is explained in a later part of the chapter.
Because a constructor is a function, you can pass parameters to the constructor to add data to your
object. For example, the following code creates a
Date
object containing the date 1 January 2014:
var myDate = new Date("1 Jan 2014");
How object data is stored in variables differs from how primitive data, such as text and numbers,
is stored. (Primitive data is 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 = [0, 1, 2];
var mySecondArrayRef = myArrayRef;
myArrayRef[0] = 100;
alert(mySecondArrayRef[0]);
First you set the
myArrayRef
variable to reference 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 first element of the array to
100
, as shown here:
myArrayRef[0] = 100;