Anda di halaman 1dari 15

Introduction to this JavaScript Tutorial

At present, JavaScript has a number of cool features, some that are useful and even a few that can
be essential to a complex web site. In the future, dynamic client-side processing and interaction via
web scripting will become very important, especially in combination with Cascading Style Sheets in
level 5 browsers and beyond. JavaScript is the language of choice for that role. Be aware that
JavaScript has its limitations, however, such as the browser settings (called the object model) in
which it operates. The browsers' object model imposes many limitations on what JavaScript can do at
present. (More on this later.)

Microsoft has written a JavaScript look-alike called JScript, and they are simila enough that most
features of JavaScript run on the Explorer browser. It is hard to know what will be the essential
languages of web in the future, whether they will still be Perl, Java and JavaScript or one or more of
these will have passed on. Almost certainly, new languages will make inroads, or perhaps current
contenders, such as Visual Basic and Python will grow in importance.

However, JavaScript is a good thing to learn right now, because whatever its role will be in the future,
by learning it you will become familiar with the web scripting environment called the Document Object
Model, or DOM, that has been codified by the World Wide Web Consortium (the W3C) and
implemented in the Netscape Navigator and Microsoft Explorer web browsers. At present, JavaScript
is gaining in popularity and in functionality with each new browser generation release, so it may be
the key to your next job.

JavaScript occupies a middle ground between CGI-scripting languages (such as Perl) and the full
applications programming environment of Java in the web programming universe. JavaScript allows
you to implement some dynamic features in the web environment on the client-side (i.e., without
having to send or get any information from the server). However, as stated, the functionality of
JavaScript in a web browser is presently limited by the current W3C Document Object Model (DOM).
With later releases of the browsers, the functionality of JavaScript will increase. More on this and the
DOM later.

About this tutorial

This JavaScript tutorial was written by Michael Peterson in the spring of 1999 while working on
towards a Master of Information Science degree in the School of Library and Information Science at
Indiana University (Bloomington). It is intended to act as a supplement to the introductory JavaScript
tutorial of Dr. Howard Rosenbaum< and to Jen Burroway's tutorial. By no means is this tutorial
comprehensive. It covers those features that I find to be most important (that are not covered in the
other tutorials above) or most interesting. For a complete reference to all features of JavaScript, I
heartily recommend Danny Goodman�s excellent book, The JavaScript Bible.

All source code in this tutorial is my original work and is freely available in parts or in whole to anyone who
wishes to copy and use it. The tutorial examples are best viewed with a level 4 or 5 browser. Code that will not
work properly in earlier browser versions is generally noted beforehand.

The best online reference for Javascript is the Netscape Developer site.

Short History of JavaScript

JavaScript was created by Brendan Eich at Netscape in 1995 and first appeared in the Netscape Navigator 2
(NN2) browser. The NN2 version is now called JavaScript 1.0, but in its earliest incarnation, before the Java
revolution, it was called LiveScript. With each new Netscape browser level, new JavaScript features have been
implemented. NN3 implements JavaScript 1.1 and NN4 implements JavaScript 1.2. Each new release is
backward compatible, but has many features not recognized in older browsers

Netscape Microsoft

JavaScript 1.0 NN2 IE3 (early releases)

JavaScript 1.1 NN3 IE3 (later releases)

JavaScript 1.2 NN4 IE4

As Microsoft entered the browser wars, it too implemented a scripting language, called JScript, that is very
similar to Netscape�s JavaScript. Internet Explorer (IE) 1 and 2 did not have JScript capability. Early releases
of IE3�s JScript are virtually equivalent to JavaScript 1.0, while later ones are JavaScript 1.1 compatible. IE4
JScript is compatible with most features of JavaScript 1.2, but has features that go beyond JavaScript 1.2.
These features are a result of the new and more extensive Document Object Model (DOM) in IE4 compared to
NN4. Likewise, there are some features of JavaScript 1.2 that are not present in JScript (such the <LAYER>
object).

In response to the need for compatibility between the browsers, a standard JavaScript/JScript language, called
ECMAScript (typically pronounced eck'-ma) has been codified. This core language is basically equivalent to
JavaScript 1.1 and promises have been made by the browser makers to keep all future browsers compatible with
at least this much.

The architecture of JavaScript

As will be discussed in another section, the Document Object Model (DOM) is the architecture around which
JavaScript operates. The DOM defines what aspects of a browser window and a document within a window are
scriptable (meaning that you can change them on-the-fly without having to change the html source code or load
in a new page from the web server). For example, images are scriptable in JavaScript in the sense that an image
can be changed via a mouse rollover. In order to be scriptable, an html feature must be loaded as an object into
the browser�s document object model. The DOM is predefined by the browser makers and cannot be modified
by a "JavaScripter".

Some things, such as paragraphs of text set off by <p> </p> tags, are not objects in the current Netscape (NN4)
DOM and therefore are not scriptable. However, in Netscape they can be made scriptable by using the
<LAYER> object, which is not present in the IE DOM implementation. NN4 also allows you to alter the
position of elements (such as a paragraph) through change the CSS-P (Cascading Style Sheets - Positioning)
properties. Layers and CSS-P will not be discussed in this tutorial, however. Everything is a scriptable object in
IE4 and IE4. The IE DOM will probably be adopted by Netscape with their level 5 release due in late 1999.

< The different competing browser implementations and the creation of novel features with each new browser
release has created problems of incompatibility. In fact, the two central frustrations of working with JavaScript
are 1) the limitations of the DOM in the current browsers and 2) incompatibilities between NN and IE and
incompatibilities between v. 1.0, 1.1 and 1.2.

JavaScript is a scripting language, not a full-fledged programming language like Java or C++. Scripting
languages generally have many built in short-cuts and features tha are taken care of by the system as opposed to
having to be explicitly declared and tracked by the programmer. While Java is a full-fledged applications
programming language, JavaScript can do many things in the browser environment that Java cannot. Java and
JavaScript should be viewed as complementary and the latter is much easier to learn for the novice programmer.
Likewise, there are synergies between using JavaScript for some things (such as passing values and doing
client-side data entr validation) and a CGI-program (via Perl or some other language) for server-side processing.

Like Java, JavaScript is object-oriented. In its simplest meaning, object-oriented means that items in the
program (such as buttons, textfields and images in a browser window) are abstracted as objects and that the
program runs by means of objects talking to one another. In an object-oriented setting, the objects are related to
one another in a hierarchical fashion. For JavaScript, the relationship of the browser objects is predefined by the
DOM, as shown in this figure.

Note for programmers familiar with object-oriented settings:

The DOM used by JavaScript is a containment hierarchy, not an inheritance hierarchy as is implemented in Java
and C++. Essentially, this means that the hierarchy is used only to set up pathways for referencing objects in the
DOM, but objects do not inherit methods or data properties from their superclasses. To compensate for this
situation, all methods and variables in JavaScript are public (to put it in Java terms). The distinction between
class (static) methods and instance methods is maintained in JavaScript.

The Document Object Model (DOM)

To write web scripts in JavaScript, there are two things you must be familiar with:

1. The core language of JavaScript


2. The Document Object Model

The core language is composed of the syntax of the language, control structures (if statements, for and while
loops), the standard variable types (var and arrays) and the global functions that are available (such as
parseInt()). The core language has been standardized as ECMAScript. This standardization was possible, in
part, because Microsoft's JScript and Netscape's JavaScript are essentially identical in the core language. This
uniformity is not the case for the DOM implemented by the Netscape and Microsoft browsers, at least as of
NN4 and IE4. There may be a convergance of DOM implementation in the future, which the W3C will codify.

The DOM

The DOM is the architecture of in-built objects that the core language can manipulate. As your web page loads
into a browser, items in your page that are objects in the DOM get loaded into the browser's object model as
scriptable objects.

A scriptable object is one that can be accessed by means of your script. For example, suppose I define a text
entry box in a form. As the page loads, the browser creates a scriptable textbox object and a form object in its
memory. If I create two text entry boxes in my html, then the browser creates two textbox objects in its
memory. JavaScript code on your page can now access those object.

Which aspects of your html code become scriptable objects in the memory of the browser is dictated by the
DOM. In NN4, for example, text inside <p> </p> tags is not a scriptable object, because there no "p" or
"paragraph" object defined in the current Netscape DOM. (This will change.) Nor is there a "table" object, so
tables are not scriptable objects. Images (in NN3+), links, forms and text entry boxes are some of the objects
that are defined in the DOM. It is likely that almost all tags will become part of the DOM in future browsers, in
which the power of JavaScript will grow accordingly.
The DOM defines a hierarchical relationship between (almost) all of the objects that are defined in the DOM
architecture, which is shown in this figure. Notice that at the top of the hierarchy is the window object. The
window is the container for everything, including the toolbars (the "chrome", such as the menu and navigation
buttons) and the document.

The document object lies one step below the window object; it has three siblings (history, toolbar, and location)
and is the container for (almost) all of the rest of the objects, such as forms, images, applets and links.

In the DOM defined in NN4, there are 4 other scriptable DOM objects that are not part of the window object
hierarchy: the navigator object, the plugin object, the mimeType object and the screen object.

As I will only be using the navigator object of these extra objects in this tutorial, I won't discuss these here,
except to say that the navigator object in IE4 (and future releases of NN?) is part of the window hierarchy. In
the IE4 model, it is contained by "Window" at the same level as the document object. This does not create a
cross-platform scripting problem, however, because the window reference is optional when referring to objects
in your script (see below). Thus, when referring to the navigator object, simply start the reference with
navigator, instead of window.navigator, and your script will work in both browsers.

Referencing Objects

In your scripts, you will frequently be referencing objects (remember: JavaScript is an object-oriented
language). The DOM hierarchy provides a road map of how to refer to any particular object via the dot syntax.

This is how you reference the document object:


window.document
or
document

Since there is only one window object, we can leave off the "window" reference and the browser still knows
which document we are talking about (Note: this changes when there are frames).

Now, suppose you have the following html code:

<body>

<form name="boxes">
Enter first name: <input type="text" name="fName"> <br>
Enter last name: <input type="text" name="lName">
</form>

</body>

How would you reference the first text entry box? One way is:
document.boxes.fName

Look back to the DOM hierarchy and you will see that to get from the top window to a text object you must
follow this path:
window --> document --> form --> text, or using dot syntax:
window.document.form.text. (Or just document.form.text.) However, as there can be more than one form
in a document and more than one text field in a form, we cannot simply use "form" and "text" to cite them.

Instead, we should name the form and text boxes and cite them by their names, which leads to (leaving off the
optional "window" reference):
document.boxes.fName
to reference the first text entry box.

There is another way, however, which you should be aware of, so that you can read other people's scripts and
because this other way is a little easier for some objects. For cases where an object type can be present multiple
times within a parent object (such as multiple text boxes in a form), those objects can be referenced by their
location in the DOM element array that is automatically created in its parent object by your browser. This is
easier to demonstrate than to describe, so here's what I mean:

To reference the first text box in the code above this way, you would write:
document.forms[0].elements[0]

This can be read as: the first (scriptable) element (such as a checkbox, a text box or a button) in the first form in
the document. An array is like a small two-column table of entries. The "[0]" notation is array notation for the
first element of the array, because arrays start with the zeroth element. See the section of this tutorial on arrays
for more information.

To reference, the second text box, you would write:


document.forms[0].elements[1]

The array referencing of objects can be used whether or not the object has been given an explicit name. Also
notice that the array names are plural, not singular. It is generally advised that you give names to your html tags
(using the "name" attribute) that you will be referencing in your scripts. However, using the array notation for
forms is somewhat common.

As a last test of this concept, how would you reference the second check box in the following html code:

<body>

<form name="boxes">
Enter first name: <input type="text" name="fName"><br>
Enter last name: <input type="text" name="lName">
</form>
<br>
<form>
Are you a student?
<input type="checkbox" name="fred">Yes
<input type="checkbox" name="barney">No
</form>

</body>

Answer:
document.forms[1].barney
(Or document.forms[1].elements[1])

The Three Facets of Objects

Objects in the DOM have three important facets you must know about in order to write JavaScript code:
properties, methods and event handlers.

Properties
Properties are data elements of objects. For example, one property of a text object is its name. The value of the
name property is what you assign it to be in your HTML code or it is blank (null) if you did not give it a name.

DOM objects vary in what properties they possess. For example, here is a comparison of some of the properties
of the document object and the text object:

Document Text
alinkcolor

bgcolor defaultValue

forms[i] form

images[i] name

links[i] type

title value

URL

There are three important things to know about properties: 1) whether they are gettable, 2) what value they
return when they are gettable, and 3) whether they are settable. Properties that are gettable only are also called
read-only.

To get a complete listing of the properties of objects and how these properties behave you'll need a book like
Danny Goodman's JavaScript Bible or you can peruse Netscape developer's online JavaScript documentation.

As an introduction, we'll sample one property of each object from the table above. Th bgcolor (background
color) property of the document object is both gettable and settable and returns a hexadecimal triplet string
corresponding to the current color.

To get the current value, you would write:

var c = document.bgcolor

the variable c will be a string such as "#ffcc53". My fade-in script demonstrates the use of the bgcolor property.

To set the bgcolor property, you would write:

var c = "#212121"
document.bgcolor = c

or just:
document.bgcolor = "#212121"

The defaultValue property of a text object corresponds to the text that is displayed inside the text box. It is
gettable--it returns the string set in the value ttribute--but it is NOT settable (in your JavaScript script, I mean; it
is, of course, settable in the html <input> tag). This means that you can write:

tt>var dv = document.forms[0].moe.defaultValue
and dv will be set to the default value you specified in your code:

<input type="text" name="moe" value="shamrock">

which is "shamrock" in this case.

However, the code

var dv = "4 leaf clover"


document.forms[0].moe.defaultValue = dv

will do nothing, because you cannot change the defaultValue once the html code has been written and the page
has loaded. Don't despair, though, because you can change the current value of the textbox by setting the value
of the "value" property:

document.forms[0].moe.value = dv

Methods

Methods are built-in actions or functions that an object can perform. As with properties, what built-in methods
an object can perform differs for every object. Again, let's visit the document and text objects and look at some
of their methods:

Document Text
clear()
blur()
close()
focus()
open()
select()
write()

First, note that methods have a trailing set of parentheses after them. That is standard notation, but realize that
some methods take arguments, or values, inside the parentheses, while others do not. We will look at both
kinds.

var text = "This is a new page"


document.open()
document.write(text)
document.close()

These three document methods are typically used in conjunction to write new content to a page. The open()
function opens a layout stream for writing, write() writes to it and close() closes the writing stream. [Note:
document method open() does not open a new window -- that is the job of the window method called open().]

The document write() method takes a string argument and writes that string to t page. In the above example,
we gave it the variable "text", which contains a string, bu could have also given the write() method the string
directly, like so:

document.write("This is a new page")


The text object method focus() is used to place the cursor into a specific text box. The opposite of focus() is
blur().

See this script for an example of how the text object focus() method can be useful for showing the user what
box needs to be filled in.

Event Handlers

JavaScript is an object-oriented event-driven programming language. This means that JavaScript code
responds to user-initiated events by creating and manipulating objects (and their data values).

Most objects in the DOM have specific events to which they can respond. For each of these events, there is a
corresponding event handler which catches the event and points the script to what it should do in response. To
respond to an event you need to register an event handler in your HTML code.

For example, one event that can occur is the famous "mouse-over", when your mouse cursor enters the territory
of some screen object. The event handler for that event is called onMouseOver=. The trailing equals sign is
conventional notation when referring to the handler generically.

Here's how the onMouseOver= event handler is registered in a link object:

<a href="somefile.html" onMouseOver="someFunction(); return true">*text or image \


here*</a>

When a mouse-over event occurs for this particular link object, the JavaScript function "someFunction( )" is
called. This function would be one that you as the script-writer defined elsewhere in the page. This event
handler is peculiar in that it requires a "return true" statement at the end in order to complete successfully
(onSubmit= and onMouseOut= require this as well).

As with properties and methods, each object has a different set of event handlers that are available to it. Some
objects, such as the document object, have no event handlers available. See the event handler table for a
complete listing of handlers, what objects they can be registered for and in which html tags they go.

The Array Object

Arrays are data structures that store information in a set of adjacent memory addresses. In practice,
this means is that you can store other variables and objects inside an array and can retrieve them
from the array by referring to their position number in the array. Each variable or object in an array is
called an element.

Unlike stricter languages, such as Java, you can store a mixture of data types in a single array. For
example, you could have array with the following four elements: an integer, a window object, a string
and a button object.

In addition, JavaScript arrays are always expandable -- meaning that the number of elements in a
JavaScript array is not constrained after the array is first declared or initialized.

Why should you learn about arrays? Here are three good reasons:

1. They can greatly simplify your programming [how?];


2. The DOM stores objects as arrays and you can reference them as elements in an array
[how?];
3. You can store small tables of information in them [how?].

The details of each of these points will be explained below.

To reference an element in an array, one appends square brackets to the end of the array name. For
example, let us name the array mentioned above "arrayList". It's structure would look like this:

arrayList[0] = 7 // an integer
arrayList[1] = newWind //a window object ref
arrayList[2] = "blue suede shoes" // a string
arrayList[3] = input // a button reference

(where input = newWind.document.formName.buttonName)

The notation arrayList[1] is read "arrayList sub 1".

The position number of an element in an array is called the index number. Note that the first element
in an array has index number 0, not 1. This is called zero-based indexing and can be confusing to
novice programmers. The index number of an element is one less than it's position. For example,
the third element of arrayList has index number 2. Thus, the string "blue suede shoes" is the third
element in arrayList. Forgetting this can lead to what are called "off-by-one errors".

Creating an Array

In JavaScript, arrays are objects and they can be constructed in one of three ways.

1. JavaScript allows you to instantiate an array using the "new" operator, as follows:

arrayList = new Array(4)

This creates a new array called "arrayList" with 4 empty elements. Note that by declaring an array
this way, you are not limited to only 4 elements--you can always expand the array. Specifying the
number of elements is optional, so you could also write:

arrayList = new Array()

To define the elements of the array, you would then specify the elements. For example to make an
array of book titles (which would be string objects in JavaScript), you might write:

books = new Array(5)


books[0] = "Jane Eyre"
books[1] = "The Stranger"
books[2] = "Oliver Twist"
books[3] = "Rebecca"
books[4] = "Stranger in a Strange Land"

You could also add:


books[82] = "The Mote in God's Eye"
This is allowable in JavaScript. By doing this, you would have expanded the array to have 83
elements and elements 5 through 81 would be empty (null) elements.

This method is compatible with all versions of JavaScript.

2. The second way is to supply the elements as parameters to the array constructor:

books = new Array("Jane Eyre","The Plague","Oliver Twist","Rebecca","Stranger in a


Strange Land")

Note that there are no spaces between the parameters.

For long arrays, I do not recommend using this method due to the inability to write single line
statements over many lines. (In JavaScript, unlike most other programming languages, a carriage
return (newline) is considered the end of the programming statement. Most other (C-based)
languages mark the end of programming statement with a semi-colon.)

3. In JavaScript 1.2 environments, you can also create an array using brackets to specify the
elements to be put in the array:

arrayList = [ 2, 4, 15, 'a', "once upon a time" ]

This statement creates an array called arrayList with 5 elements. No "new" constructor statement is
required.

The first three elements are integers, the fourth is a character and the final element is a string. Thus,
the value of arrayList[3] is the character 'a'.

The Virtues of Using Arrays

Arrays simplify your programs

Suppose you wrote a web page asking users what their favorite book was. In response to their answer, you
would like to respond with: "That is one of my favorite books too!" or "That one is not on my list of favorites."

Here is one way you could check the user's input against your list of favorite books:

var input = document.formName.textFieldName


var fav1 = "Jane Eyre"
var fav2 = "The Stranger"
var fav3 = "Oliver Twist"
var fav4 = "Rebecca"
var fav5 = "Stranger in a Strange Land"

if ( fav1 == input ) {
document.write("That is one of my favorite books too!");

} else if ( fav2 == input ) {


document.write("That is one of my favorite books too!");
} else if ( fav3 == input ) {
document.write("That is one of my favorite books too!");

} else if ( fav4 == input ) {


document.write("That is one of my favorite books too!");

} else if ( fav5 == input ) {


document.write("That is one of my favorite books too!");

} else {
document.write("That one is not on my list of favorites.");
}

This method is very space wasteful and repetitive. Imagine how long and ugly it would be if you had
15 favorite books. Or 30.

An alternative way to write this script would be:

if ( fav1 == input || fav2 == input || fav3 == input || fav4 == input || fav5 == input )
{
document.write("That is one of my favorite books too!");

} else {
document.write("That one is not on my list of favorites.");
}

By using the Boolean OR operator, ||, this method saves a considerable amount of space over the
last one. However, it still becomes bulky quite quickly as the number of variables you want to test
increases. In addition, this method runs into the problem of not being able to write single code
phrases over multiple lines in JavaScript. (Meaning that long lines must be written on a single line--
making them hard to see and a possible cause of error in some Unix text editors.)

The right way to write this script is with arrays. First you would define an array with the list of
your favorite books:

books = new Array(5)


books[0] = "Jane Eyre"
books[1] = "The Stranger"
books[2] = "Oliver Twist"
books[3] = "Rebecca"
books[4] = "Stranger in a Strange Land"

Then you use a for loop to iterate over each element of the array and compare it to the user's input. The length
property of the Array object returns the number of elements in the array and can be used to create the
conditional statement in a for loop:

for (var i = 0; i < books.length; i++) {


if (books[i] == input) {
document.write("That is one of my favorite books too!");
break;
}
} //end for loop

if (i == books.length) {
document.write("That one is not on my list of favorites.")
}

The for loop iterates over each element of the array "books". As it does so, it checks each element to
see if it matches the user's input. If it matches, it tells the user with a document.write() command
and then uses a break command to jump out of the for loop.

break is an inbuilt JavaScript command that causes the program to jump out of a repetition loop--that
is, a for loop or a while loop. Without the break statement, the for loop would cycle through all five
books, even if the an earlier book had matched the user's input. Put another way, without the break
statement, the variable i would be equal to 5 when the for loop was finished executing. In that case,
the if statement after the for loop would evaluate to true.

With the break statment, if the user input matches, say, books[1], then when the for loop was finished
executing i would be equal to 1. A break statement causes the flow of program execution to
immediately leave the repetition loop that contains it. The first statement after the closing bracket of
the for loop is the next thing to be executed. In this case, the if statement following the for loop would
be tested and it would evaluate to false.

The DOM stores objects as arrays and you can reference them as elements in an array

Many objects in the DOM have elements that can occur multiple times. For example, a window can
have multiple frames. A document can have multiple forms or multiple images. A form can have
multiple "widgets", which in the DOM are called "elements". To help keep track of them all, the DOM
automatically constructs an array with a reference to each element for each object that can have
multiple elements. This array is stored as a property of the parent element and it can be referenced
like any other property: with dot syntax.

Suppose you load into your browser a document that has 3 images. "images[i]" is a property of the
document object. Thus the first image (first here means first to occur in the html source code) can be
referenced as:

document.images[0]

Here are a few of the arrays elements in the DOM and their parent containers:

Window object
frames[i]

Document object
applets[i]
forms[i]
images[i]
layers[i]
links[i]

Form object
elements[i]
You can store tables of information in arrays

A single array can be thought of as a single row of values in a table. How then can we add more
rows to our "table"? We could just define a set of arrays, like this:

var row1 = new Array()


var row2 = new Array()
var row3 = new Array()
var row4 = new Array()
var row5 = new Array()

and then specify the elements of each array.

Another way to do it is to create an array of arrays or create an array of user-defined objects.

An array of arrays might look this:

var book = new Array()


book[0] = new Array()
book[1] = new Array()
book[2] = new Array()
book[3] = new Array()
book[4] = new Array()

Thus, each element of the array book is itself another array--in other words, we've created an array of
arrays.

Suppose we wanted to keep a table of information about our five favorite books:

Name Author Date of Publication

Book 1 Jane Eyre C. Bronte 1847


Book 2 The Stranger A. Camus 1942
Book 3 Oliver Twist C. Dickens 1846
Book 4 Rebecca D. DuMaurier 1938
Book 5 Stranger in a Strange Land R. Heinlein 1961

Using an array of arrays, we would input the data this way:

book[0][0] = "Jane Eyre"


book[0][1] = "C. Bronte"
book[0][2] = "1847"
book[1][0] = "The Stranger"
book[1][1] = "A. Camus"
book[1][2] = "1942"
book[2][0] = "Oliver Twist"
book[2][1] = "C. Dickens"
book[2][2] = "1846"
book[3][0] = "Rebecca"
book[3][1] = "D. DuMaurier"
book[3][2] = "1938"
book[4][0] = "Stranger in a Strange Land"
book[4][1] = "R. Heinlein"
book[4][2] = "1961"

While this may look confusing at first, it becomes easier to understand when you remember this
mantra: "row first, column second". Thus, the string "C. Dickens" is in row 2, column 1 (remember that
arrays are zero-indexed, so that the first row and first column are labelled 0, not 1.)

Creating an Array of Objects

An alternative way to bring in a small table of data to your web pages is to create an array of objects.
In JavaScript, you can define your own objects, complete with their own properties. To create a new
object, you must write a constructor method and then use the new operator to create objects from it.

Here is an example constructor method:

function bookInfo( name, author, pubDate ) {

this.name = name;
this.author = author;
this.date = pubDate;
}

This function creates an object called bookInfo. bookInfo receives three arguments and assigns
those to its three properties: name, author and date. You can now reference the properties of this
user-defined object the same way you reference properties of objects in the DOM--using dot syntax:
bookInfo.name

As the constructor method can be used to create as many different bookInfo objects as we want, let
us now create an array of objects using the constructor method we just defined:

var book = new Array();


book[0] = new bookInfo("Jane Eyre", "C. Bronte", "1847");
book[1] = new bookInfo("The Stranger", "A. Camus", "1942");
book[2] = new bookInfo("Oliver Twist", "C. Dickens", "1846");
book[3] = new bookInfo("Rebecca", "D. DuMaurier", "1938");
book[4] = new bookInfo("Stranger in a Strange Land", "R. Heinlein", "1961");

What did this do? It created five new "bookInfo" objects from the bookInfo constructor object and put
each of those objects in the array "book". The new keyword automatically creates a new object by
calling the constructor method specified after it (in this case the method "bookInfo()"). A constructor
method automatically returns a reference to the object (this is predefined in the JavaScript
language). This reference is what gets stored in the array elements, book[0], book[1], etc.

In other words, book[0] is two things: 1) an element of the array "book" and 2) a reference to a
bookInfo object (that has three defined properties). Ditto for book[1], book[2], book[3], book[4],
except that they all refer to different bookInfo objects.

Anda mungkin juga menyukai