JAVASCRIPT REFS:
http://Bignosebird.com/
http://javascript.internet.com/
http://www.javascriptguide.com/
NOTE:
I am beginning to integrate FIBs into this LM, so you will see text, like
browser (), which is simply a reminder
to me to turn this into an FIB, e.g. ___________(10)
when
I rewrite the module. Don't let this confuse you; you are lucky;
the answer is there in front of you, but future students will have to refer
to hints/answers to find this after I rewrite.
{ADD SAQS}
Drafted:
4/26/00; major rewrites: 3/20/01, 4/14/01;
11/20/02
Currently
being created!
COSC 330
LEARNING MODULE
VII
INTRODUCTION TO
JAVASCRIPT
JavaScript
is a very high level, object based scripting language that was specifically
designed to provide interactivity and animation to Web pages.
It currently is used in two contexts, for client-side scripts embedded
in HTML documents (the primary use) and for server-side scripts.
It
has the same language syntax as Java (and C and C++); however, being a
VHLL (1)
it is much more limited than these HLL. In particular, it does not
have the object-oriented facility of access control of inheritance
(characteristic of Java and C++); for this reason JavaScript is usually
called an "object-based" language rather than an "object-oriented"
language. (
Some
texts say that the OOP facility of Inheritance can not be implemented in
JavaScript, but this is not true; see section....{}To
see the distinction between object-based and object-oriented languages
see "THE
EVOLUTION OF SOFTWARE DEVELOPMENT" in COSC 390, LM I.)(
However this distinction is debated by some, and the language is evolving
so perhaps this distinction will change. In any case, this technical
point does not affect the use of JavaScript.)
See
the Study
Guide for this learning module.
It
is CRITICALLY important to understand that JavaScript uses several terms
differently than they are used in other object oriented languages;
in order to avoid confusion I have addressed this inconsistency
in OO termanology in the study guide and reinforced it in the learning
module itself.)
The
Objectives of this learning module are to:
-
compliment
the tutorial-like introduction to JavaScript in
Moncur,
Teach Yourself JavaScript in 24 Hours
-
present the basics of
client side scripting using JavaScript
-
help the non-programmer learn to use JavaScript
to add interactivity and dynamic features to Web pages
-
help computer science students
-
understand how JavaScript
fits within the family of programming languages
-
understand how JavaScript
compares to C++ and Java in particular.
TPQ
1: Rewrite the preceding objectives in terms of personal accomplishments
to be attained after finishing the study of this learning module.
This
LM follows the sequence of chapters in
Moncur,
Teach
Yourself JavaScript in 24 Hours, (hereafter
referred to simply as Moncur)
but modifies this in order to better associate related techniques. The
sequence of presentations in this learning module is as follows.
You can click on any link to jump directly to that section.
-
GETTING
STARTED (Moncur, Part I)
-
JAVASCRIPT
BASICS (Moncur, Part II)
-
ADVANCED
JAVASCRIPT FEATURES (Moncur, Part III)
-
JAVASCRIPT
OBJECTS (Moncur, Part IV)
-
SCRIPTING
ADVANCED WEB FEATURES (Moncur, Part V)
-
JAVASCRIPT
APPLICATIONS (Moncur, Part VI)
The
Appendices
of this LM form a concise summary of the most useful
features of JavaScript, focusing on the Browser-independent constructs
that we will emphasize in this course. They present JavaScript as
a programming language (unlike this LM which introduces JavaScript in a
user-friendly introduction paralleling Moncur.)
so it will not be very intuitive to learners who have no programming
experience. However, it is recommended that you look over this
appendix before proceeding with the sections of the following LM;
this is especially true for computer science students who have experience
with C++.

I
recommend that, while reading the chapters of Moncur,
you open an HTML editor in which you can create scripts (Netscape 6 Composer,
Dreamweaver, or Microsoft FrontPage) so you can code and test Moncur's
examples as you encounter them.
GETTING STARTED
(Moncur, Part I)
1 Understanding Client Side JavaScript (
Supplements
Moncur Hour 1):
-
JavaScript
is a very high level language (VHLL) specifically designed to write
event driven scripts that compliment HTML. Review the overview
of JavaScript in LM VI. In general JavaScript has three
manifestations (explained in more detail in section
1.1.A of the appendix.):
-
Core
JavaScript, the base JavaScript language, manifested in ECMAScript
specified by the ECMA, the European association for standards.
Unfortunately, despite these efforts to standardize Javascript,
this has only partially occured in the specifications of ECMA.
The latest stanard JavaScript 1.5 follows the ECMA-262
revision 3; it is supported with Netscape 6 and later.
Microsoft has charateristically tried to usurp JavaScript by creating a
version called "JScript" which is partially compatible with the standard
version; however, Internet Explorer 5.5 and later supposedly supports
"most of the features of JavaScript 1.5".
-
Ref:
Netscape's
Core JavaScipt Guide.
-
Ref:
Netscape's
Core JavaScipt Reference.
-
Client-Side
JavaScript (CSJS), an extension of Core JavaScript that is used
to write code that is embedded within HTML documents
that are to be viewed by browser (the "client"). CSJS
is, by far, the most commonly use of JavaSript.
Virtually
all of Moncur and
this LM focus on client-side scripting.
-
Server-Side
JavaScript (SSJS), an extension of Core JavaScript that enables access
to file systems and databases located on servers in a distributed computer
system. In server side scripting, like CGI scripting, the
processing occurs in
(2) programs, compiled
from JavaScript, that reside on the server. JavaScript can be used
this way to reduce the dependence on the user's system. (However,
this is not nearly as popular as CSJS.)
In
COSC 330 we will be primarily concerned with Core JavaScript and CSJS.For
more
information on the distinction of these three versions of JavaScript
see: http://developer.netscape.com/viewsource/husted_js/husted_js.html
SAQ
1 : What is the (a) similarity and (b) difference between Core JavaScript,
CSJS, SSJS?
-
The uses
of JavaScript are restricted to Web pages because the language was
esplicitly designed for this purpose.
Moncur,
Hour 3 gives a nice overview of the
primary uses of Javascript including, in order of importance (according
to Tony,):
-
improving
the human interface of a Web site,
-
incorporating user interactivity,
e.g. automating and/or validating forms, interactive banners
-
providing output messages on
a Web page, in alert boxes, in the browser status line,
on the pointer (as it passes over a Web page element), etc.
-
validating input from HTML forms
(which can also be completely processed by JavaScript).
-
creating
complex applications.
-
animating graphics like responsive
(rollover) buttons or a cursor that leaves a trail of bubbles,
-
provide interactive Web page elements,
like add banners
-
detecting installed plug-ins
and notifying the user if a particular plug-in is required, and
-
detecting the type of browser
and displaying content customized for that particular browser.
-
Where CSJS is used: JavaScript,
being designed to complement
(3), is inherently associated
with HTML so it appears in three distinct places:
-
within an HTML document, where
it is manifested three ways:
-
Scripts normally appears within
the body of an HTML document. Such JavaScript code is
delimited
with the <script>...</script> tags. An example
of the syntax of an embedded script is
<script language="JavaScript
1.5">
<!--
document.write("Hello Web
Surfer!");
//-->
</script>
-
This
"scripting"
distinguishes CSJS from other programming languages, which are typically
used to write stand-alone programs, i.e. there are no CSJS programs,
only scripts within HTML documents. These are processed when
the page is loaded and the output is typically displayed as part
of the document itself.
-
Note that, in the preceding code, the
only JavaScript is "document.write("Hello Web Surfer!");"; the
rest is
(4) that tells the browser that
the tags enclose JavaScript, which must be passed to the browser's JavaScript
interpreter to be executed. If the browser does not have a JavaScript
interpreter, the browser does not support JavaScript.
-
Scripts should be coded within HTML
comment fields (delimited by the tags <!-- and //-->)
so that old browsers, that do not support JavaScript, will ignore the JavaScript.
This is, in fact optional, but is a good habit, even if you do not expect
the users of your Web site to have old browsers.
-
Any number of scripts may be embedded
within an HTML document, using multiple script tags.
-
Functions are written by the
HTML author and are typically defined within the head of an HTML
document; they are thus independent of the scripts within the HTML program.
Note that functions are not executed when the HTML document is first displayed
in the Browser; instead, they are invoded (called) from the scripts
within the body. Being independently placed in the head, they
can be called any number of times from any script in the HTML document
body or by other functions. (See
Moncur,
Hour 4. and use Find in Frame on Appendix
A to see the many references to "function".)
-
event handlers are JavaScript
statements that
respond
to events that may occur while an HTML document is being displayed.
Examples include a mouse click (the handler is onClick), the mouse
being moved, the page being loaded, etc. (See the list of events and handlers
in Appendix A,
section 5.E.) The event handler defines the JavaScript response to
the event; they are generally coded as functions. Event handlers
are typically invoked from within HTML tags. For
example, if you want a hyperlink to change
colors when the cursor passes over it, you could define a JavaScript function
called changeColor(), and call (invoke) it from within the hyperlink
tag, using the onMouseOver event handler, e.g.
<a href="" onMouseOver="changeColor();">
SAQ
: What is the (a) similarity and (b) difference between scripts,
functions, and event handlers in JavaScript.
-
in separate files. that have
a .js extension. This allows the scripts and functions,
coded within these files, to be accessed by any HTML document (unlike
JavaScript embedded within a single HTML document) i.e. JavaScript in
.js
files can be called from any HTML document, but JavaScript
within an HTML document can only be called from within that document.
All of the JavaScript constructs mentioned in the previous section,
,
, and
(5) can be used in these files.
-
JavaScript implements all
the "constructs" of structured programming
languages, the predecessor of object-based and
object oriented programming languages. ("Constructs" is simply a
term to describe the programming elements from which programs are "constructed".)
-
Large
programs are broken down into smaller modules (the objects and functions
of JavaScript).
-
JavaScript
has standard control structures (sequence, selection, and repetition)
of structured programing languages and uses ANSI Standard C syntax,
the same syntax for these as in C, C++, Java and others.
-
COSC
330 students, who are not computer science majors need not worry about
the theoretical details of such languages.
They can be comfortable in the fact that all the JavaScript code they develop
will be structured, and object based (but NOT
object oriented!).
-
The termanology of JavaScript overlaps
that of other languages (especially Java and C++) but, unfortunately,
there
are confusing inconsistencies between these languages. See the
Appendix, Section
1.B.a and the Study
Guide, item 3 for details. (Unfortuantely this is not mentioned
in Moncur.)
-
Alternatives to JavaScript include
the scripting
languages mentioned in LM I. Moncur only mentions the
most popular:
-
(6) , the HLL designed for distributed
object oriented processing. It is a more general language; Web applets
are only one of its applications.
-
(7) and
(8) are specifications
rather than languages. These were discussed in LM I, section
4.1.C and section
4.2.B.e.
-
Be sure to do the Exercises
at the end of Moncur Hour 1.
SAQ
: What is the difference between (a) JavaScript and Java (b) JavaScipt
and DHTML?
2. Creating a Simple Script(
Supplements
Moncur Hour 2.):
-
To create JavaScript, one needs
an editor, e.g.
-
a simple text editor like Notepad
or WordPad in Windows or
-
an HTML editor like Netxcape
6 Composer (and later versions), Microsoft FrontPage, Macromedia Dreamweaver,
etc., which make script development more efficient
and user friendly.
-
Any script, e.g. JavaScript, VBscritp,
etc., is delimited by the HTML tags, <script> and </scipt>.
-
To designate JavaScript, so that the
browser knows to start the JavaScript interpreter, the language parameter
must be specified, e.g.
<script language="JavaScript">
-
A particular version of Javascript
can be specified, e.g. languge="JavaScript1.5". If a script
does not use a new feature of a version of JavaScript later than 1.0, this
is unnecessary.
-
-
-
Semicolons are used to end
JavaScript statements, like most other programming languages. Although
this is not "required" (the enter key is recognized by the JavaScript interpreter
as the end of a statement.), it is good practice to include semicolons,
so
semicologns required in scripts written in this course.
-
Variables
are identifiers used to store values that can be accessed by including
the variable name in a JavaScript statement. The use of variables
in JavaScript is virtually identical to their use in other programming
languages.
-
Moncur oversimplifies the introduction
of variable when he uses, now = new Date() as an example.
This defines the variable now to be an "instance" of an object
of type Date; this is an advanced feature of variables (involving
the JavaScript's Object Model) that is not covered until Hour
9. It is worth noting how the "dot notation" is used,
in the OM, to designate specific methods belonging to a specific object,
e.g. now.toString() is a built-in JavaScript method, belonging
to the Date(8)
object that can used by the now object because it is of type Date
(9).
This actually leads to one of JavaScript's downsides, it's misuse of the
word "object"; this is discussed, where it is more appropriate, in
-
Variables are covered in more detail
in Moncur's Hour 5
and section 5.C. "Variables"
is a very commonly used term; to find these, in this learning module, use
the Find in Frame... facility.
-
Output, from javaScript, to a Web
page is provided by the built-in method, document.write(argument),
of the document (10)
object; the argument of this method (a text literal or
variable containing text) is displayed.
-
The
JavaScript Console, in Netscape 6 and later, is a handy
tool to practice writing JavaScript. It accesses the JavaScript
interpreter directly, allowing the user to experiment with JavaScript expressions,
methods, objects, etc. (This is a convenient feature of interpreter
based languages; in compiler based languages, one has to write a complete
program and debug it before seeing the results of executing an expression
or functions.) To try an expression, one only has to type it in the convenient
code input field on the console It is most convenient to display
results using JavaScript's alert() function, where you place
the value to be output as an argument; this will display the result in
a pop-up alert box.
-
To test a script, simply load
the HTML page where the script is embedded (11).
-
Errors in a script can have
two
distinct results:
-
an error message will be displayed,
or
-
nothing will happen. (This
"user friendly feature" prevents scripts with errors from "bombing" a Web
page, but also is of no help in finding the offending error, or, what is
worse, will not remind the developer that an error has occured!)
Before
Navigator 4.5, error messages display in a pop-up window; starting
with version 4.5, errors are displayed in the JavaScript Console.
It is advisable to set the browser preferences to automatically display
the JavaScript Console when errors occur;
this is accompllished in vaious ways, depending on the browser vesion.
-
To hide scripts from older browsers
that do not handle javaScript (now rare), simply enclose the script with
JavaScipt comment tags, just inside the <script> and </script>.
tags. The JavaScript supporting browsers are smart enought to recognize
that the JavaScript is not a comment and should be exceuted.
-
Workshop:
This is a very simple exercise on hiding scripts, as indicated in the preceding
item.
-
The
second
Q&A question in Moncur focuses on an troublsome mistake that can
be very frustrating.
3. Exploring JavaScirpts's Capabilities(
Supplements
Moncur Hour 3.):
-
The status line (at the bottom
of the browser (12))of a browser
can display three things:
-
the URLs of hyperlinks when
the cursor passes over them and
-
the function of browser toolbars
components (menus and buttons) .
-
the output of JavaScript scripts.
(See the Workshop of this hour and Hour
6.)
-
Hour 3 is actually only a preview
ofd JavaScript uses in subsequent Hours. These include
-
drop-down lists, used to get
data with forms; see Hour 14.
-
pop-up messages (alerts, confirmations,
and prompts), covered in Hour 10.
-
separate browser windows (with
JavaScript controlled content), covered in Hour
13.
-
DHTML features like layers (independent,
movable areas within a Web page), covered in Hour
18.
-
simple dynamic images, e.g.
rollovers and mouseovers, that change without reloading a page, covered
in Hour 15.
(More complex images require Shockwave, Quicktime, etc.)
-
client-side processing of data entered
in forms, one of the the simplest but most useful of JavaScript's capabilities,
covered in Hour 14.
-
detecting browser versions so
that incompatibilities of different browsers can be accommodated in HTML,
scripts, plug-ins, etc., covered in Hour
16.
-
detecting, working with, or installing
plug-ins for multimedia playback on the client, covered in Hour
20.
-
creating complex scripts, like
embedded game, covered in Hour 23.
-
This Hour's workshop
illustrates the useful technique of copying and customizing scripts,
in this case a scrolling message displayed in the browser status line.
With the plethora of scripts readily available on the Web this can be a
powerful tool for incorporating scripts in a Web site.
4. How JavaScript
Programs Work (
Supplements
Moncur Hour 4.):
-
JavaScript is typically incorporated
into HTML documents by invocations (calls) to functions and methods
that define the behavior of scripted Web page elements. The order
of execution of scripts is:
-
Scripts (JavaScript code within
<script> tags) in the the <head> section of the HTML document
are the first to be executed. Since these cannot output to the Web
page, these scripts are usually used to define functions and methods.
-
Scripts within the <body> section,
in sequential order, while the page loads and displays.
-
Event handlers are executed
when their associated event, e.g. mouseOver, occurs.
-
Functions are, along with methods,
one of the primary means of defining the behavior of JavaScript controlled
Web page elements. These were covered in in Appendix
A.
-
Moncur uses the word "parameters"
for what are more properly called arguments
(13).
-
JavaScript objects, defined
in various "object models", e.g. the core
object
model (COM) and document
object model (DOM), are built-in generic Web
page elements.
-
Objects encapsulate:
-
properties ( "attributes
(15)", is a more proper, object
oriented term) which specify the object's state and
-
methods (functions specifically
associated a particular object) which specify the object's behavior.
-
JavaScript supports three types of
objects:
-
built-in objects which are part
of the language; these are covered in Hour
9.
-
browser objects which specify
browser elements like windows, frames, buttons, etc., covered in Hour
10.
-
custom objects, covered in Hour
11.
-
The JavaScript Event Model, covered
in Appendix
A, section 7, which facilitates event-driven programming
is a relatively simple protocol for handling user interactions
with Web pages.
-
Event handlers, associated with
particular Web page elements, are specified by an attribute in the tag
that defines the element.
-
Being simple, the JavaScript event
model is
a
good way to introduce students to event-driven programming techniques.
-
As with all programming languages,
programs are developed using two types of control structures that
modify
the normal sequential execution of statements:
-
selection constructs (called
conditional statements by Moncur;
see the SAQ below) exemplified by by if statements; see Appendix
A, section 4.
-
repetition constructs which
are of two types, iteration (called
loops (16) by Moncur), covered
in Appendix A, section
4 and recursion, covered in Appendix
A, section 4.
-
This Hour's workshop
is a trivial exercise in using comments in JavaScript scripts.
SAQ:
Moncur's term "conditional" statements for if
statements is imprecise because it applies to iterative (looping) statements
as well. Explain this.
LEARNING
JAVASCRIPT BASICS (Moncur, Part II):
5. Using Variables and Functions (
Supplements
Moncur Hour 5):
-
This hour introduces modularization
and abstraction in JavaScript. Modularization means to group
related statements into a self-contained module and abstraction
means to give that model a descriptive name, i.e. the module can be referenced
(invoked or called) via that name.
-
Modularization and abstraction,
in JavaScript, are implemented with functions, a structured
programing construct. (Note that functions that are associated with
JavaScript objects are called methods
(). See section 4.C.ii,
above.)
-
Abstraction is also implemented via
the variable construct. Values are represented by a variable
in a manner identical to mathematics.
-
Functions are a named collection
of self-contained program statements that are executed together
when the JavaScript interpreter encounters the function name in a JavaScript
statement. (See Appendix A, Section
2.E.b and Section
3.)
-
In JavaScript, like C and C++, functions
have two forms, those that return a value (true functions) and
those that perform a specific task like printing (null functions).
(Strickly speaking, functions, in programming languages, return a value
via their name, i.e. the results of their execution replace their name
in the instruction they are called.)
-
True functions, in JavaScript,
are coded to return values via the return statement at the end
of the function definition; see Moncur,
Listing 5.5. and the function factorial
in Appendix
A, Section 3.B.d.)
-
Null functions do not return
values; instead they they perform a task. See the null function GreetListing
5.4 of Moncur and the null function
warning
in Appendix
A, Section 3.B.d.ii.
-
Data values are passed to functions
via arguments (sometimes inappropriately called "parameters") placed
within parentheses after the function name. Multiple arguments are
separated by commas.
SAQ:
(a) In Appendix
A, Section 3.B.d, (a) what is the argument of the function factorial
and (b) what values are returned by the two versions of factorial.
-
Functions are usually placed within
the header of an HTML document. Since statements within the header
are executed first, this insures that functions defined within the header
are defined before they are called.
-
Functions are invoked (called)
by using the function name in a JavaScript statement. These can be
invoked from within a script in the body of the HTML document (e.g.
the function Greet Listing
5.4 of Moncur) or from within another
function (e.g. the built-in function alert within Greet
of Listing 5.4)
or method.
-
Variables,
introduced in section 2.D,
above, are identifiers used to store data values that can be accessed by
including the variable name in a JavaScript statement; the use in JavaScript
is like that in other lanugages.
-
Variables in JavaScript are global
unless
they are declared within a function in which case they are local
variables with a scope limited to the function were they are defined.
-
Unlike strongly typed languages (like
Java, C++, etc.), JavaScript variables do not have to be declared,
i.e. their type does not need to be specified. This is a user-friendly
feature, but is dangerous because typing of variables, in strongly typed
languages, is means of detecting and removing programming errors.
See
the warning
in Appendix A.
-
Specifics of JavaScript variables and
their use are presented in Appendix
A, section 2.B.
-
JavaScript is a weakly typed language. which means
that variable types do not have to be declared because the JavaScript interpreter
will automatically manage this. Specifics of
JavaScript types and their use are presented in Appendix
A, section 2.C.
-
This Hour's workshop
illustrates the Input of strings, using the assignment of the prompt()
function to variables. This may seem a little mysterious to beginners
so consider this carefully.
SAQ:
What three things does line 7 of Listing
5.7 in Moncur do?
6. Using Strings and Arrays(
Supplements
Moncur Hour 6.):
-
This hour introduces the built-in
data structures, string and array, of JavaScript; they are, in fact,
JavaScript
"objects".
-
Note that, conceptually strings
and arrays are both "indexed" data structures, i.e. they are collections
of data where individual elements or sequences of elements can be designated
or accessed by their index.
-
String elements are alphanumeric
characters (letters, numbers, and symbols on a keyboard).
-
Array elements can be any homogeneous
data type, including other arrays.
These definitions are independent
of JavaScript or any computer language. These are concepts
that can be implemented in computer languages, often in subtly
different ways. In JavaScript the data types of an array are JavaScript
objects.
-
Strictly speaking, in JavaScript,
both strings and arrays are objects (equivalent to OOPL classes()),
but
JavaScript's
user-friendly character makes this really of little practical importance
- but only for people who just want to use JavaScript as a "tool" to enhance
their Web pages.
Anyone
who uses or plans to learn other OOPL should be VERY careful in relating
JavaScript to those languages, e.g., in this case, JavaScript misuses the
word "object"; see the Study
Guide, section 3.2 and Appendix
A, section 5 .
-
Moncur
does not consistently use object based syntax,
I will use object based syntax in this LM and try to point out the differences.
-
String objects implement the string
data type in JavaScript.
-
Strings, in any programming language,
are a data type for manipulating text data; see the JavaScript's
string data type in Appendix A.
-
Strings are an indexed sequence
of alphanumeric characters; the first element has an index of zero.
(Irritatingly confusing characteristic taken from C/C++!!)
-
String operations and properties
(See
App. A.5
. to
view these from the context of the overall JavaScript language.):
-
Creating strings can (unfortunately)
be done two ways. Moncur's example is:
text = "This is a test.";
text = new String("This
is a test.");
The first statement is an oversimplified
version of the second, a proper object based statement. Actually
the first statement is an assignment statement (See the next item.), but
JavaScript automatically creates an object if one does not already exist.
Anyway, although the last instruction is the most proper, the strings that
are created are identical.
-
Assignment is accomplished by
setting a string equal to a variable, e.g.
textVariable = "This is
a new string.";
overwrites()
the previous value of textVariable with "This is a new string".
As mentioned in the previous section, if an object text does not already
exist, JavaScript creates one when this assignment is executed.
-
To change the case of a string,
invoke the String object methods:
-
toUpperCase() converts all
the characters of the object associated with this method to uppercase,
and
-
toLowerCase() converts all
the characters of the object associated with this method to lowercase
e.g. textVariable.toUpperCase()would
return
"THIS IS A NEW STRING." ().
-
To determine the length of a string,
simply access its length property, e.g. textVariable.length
will give the length of the string of the object textVariable.
(
Note,
Moncur's section heading "Calculating the String's Length" is misleading.
"Calculating" is an operation and would be accomplished by calling
a method or function. Instead length is a "property"
of the string object; therefore, length has a value, although this
may not be obvious.)
-
To access and manipulate substrings:
-
To access a substrings of a string,
invoke the method substring(beginning, end)
of the object string, where beginning is the index of the
beginning of the substring to be returned and end is the
index of the character that is NOT included. For example, if a NumString
is "123456", then numString.substring( 3, 5) will return "45"().
which is NOT intuitive;
you just have to get used to this stupid convention! (Remember, JavaScript
indices start with zero; this applies to strings as well as arrays!)
To get used to the string indices, do the
exercises
on p.78 of Moncur.
-
To access a specific stringelement,
invoke the method charAt(index)().
-
To locate the beginning of a particular substring of a
string, invoke the method indexOf(stringToFind,
startLocation)(). where the second, optional,
argument indicates the index where the search is to begin.
-
To divide a string into substrings, invoke the method split(divider)().
To store these separated parts of a string, an array of strings is automatically
created by JavaScript; see section C.d.ii, below.
-
String methods not mentioned in Hour
6 (See Moncur, Appendix D.):
-
lastIndexOf
-
methods associated with HTML: link and anchor
-
methods associated with string appearance in HTML documents:
big,
blink, bold, fixed, fontcolor, fontsize, italics, small, strike, sub,
and sub.
SAQ:
Which of the preceding string manipulations are (a) accessing object properties
and (b) returning values via object methods?
-
Array objects implement the array
data structure in JavaScript.
-
Arrays, in any programming language,
are a data type for manipulating homogeneous data, represented,
in JavaScript, by primitive data types (e.g. integers, real numbers,
characters, etc.) or objects (e.g. string, other arrays, etc.).
-
Unlike strings, arrays must be instantiated,
i.e. to create an array of 10 elements called "arrayOfThings" one would
write the JavaScript instruction
var arrayOfThings = new
array(10);
where the index of the first element,
as in strings, is 0 ().
(Compare this to the declaration of a string, above.) Note that the
type of the elements in this array is not specified. Also note that,
although arrayOfThings is instantiated
(It
exists.) it is NOT initialized, i.e. the values of its elements
have not been specified. Initialization involves assigning a value
to each array element.
-
Individual array elements may be accessed
by specifying their index enclosed in bracket following the array name,
e.g.
fifthThing = arrayOfThings[4];
()
-
Array elements can be any primitive
data type or object in JavaScript. The most common include:
-
Numeric arrays are created by declaring
each element to be a number type, e.g. integer or real.
-
String Arrays
-
Array operations
-
Operations with string equivalents:
instantiation and assignment.
-
Splitting of an array is accomplished
by invoking the method of the array object; see the preceding section
on strings. JavaScript automatically creates enough arrays to accommodate
the number of
-
Sorting of arrays is accomplished
by invoking the sort()
method of the array object.
-
Array operations not mentioned in Hour
6:
-
the method join(array elements separated by
commas) concatenates the specified elements into a single string.
(See Moncur, Appendix D.)
-
the method reverse(arrayName) reverses
the order of the elements of the array argument. (See Moncur,
Appendix D.)
-
Five ECMA-262 methods that are not in Moncur include:
charAt(),
charCodeAt(), fromCharCode(), toString(), and valueOf().
(
You
are not responsible for these.)
-
Hour Six's workshop
illustrates the use of strings to create the dynamic Web page effect
of a scrolling message in the status line of a browser window.
-
Note that there is a more sophisticated
script for a scrolling message on page 259 of Moncur.
-
The Workshop in this Hour uses a recursion
function, ScrollMessage, which
(I think) is premature, i.e. recursion, a form of repetition, has not been
covered; in fact ignores recursion all together, so I don't think
it should be used in an example. See recursive
functions in Appendix A and
SAQ:
If a string is an array, what is the point of creating an array of strings?
7.
Selection control structures (
Supplements
Moncur Hour 7, Testing and Comparing Values.):
-
This
hour, along with Hour 8, is straightforward because control structures
are not associated with objects and therefore, have no inconsistencies
in terminology that we've had to deal with previously. In fact for
those who have experience with C, C++, or Java, already know everything
in this chapter because JavaScript, like those languages, uses ANSI standard
C syntax.
-
There are only two fundamental structured control
structures, selection and repetition. (See Appendix
A, section 4.) This hour introduces the selection
construct (See Appendix
A, section 4.A.). Repetition will covered in Moncur
Hour 8, below.
-
All control
structures, selection and repetition test boolean expressions
and thus control the flow of execution of program instructions.
Such Boolean expressions can consist of:
-
a simple constant, either true or
false
-
a single Boolean variable, which can have
only two values, 1 (for "true") or 0 (for false").
-
a complex conditional statement containing
comparison
operators (==, !=, <, >, >= or <=; called "conditional operators"
by Moncur.
Also,see Appendix
B, section 2.) and/or Boolean operators (&&, ||,
!; called "logical operators" by Moncur.
Also, see Appendix
B, section 2.) For example the conditional statement represented
by the following Boolean expression
(Grade >= 0) && (Grade <=100)
would select the
values of Grade between 0 and 100 ()
-
Selection, in JavaScript (as well as C, C++, Java,
and most programming languages) is implemented with three constructs.
-
most fundamental selection construct is the
if-else
statement (called if-then-else in some languages); see Appendix
A, section 4A.
-
the switch
statement, which is a concise, useful "simplification" of what would
be a complex nesting of if-else statements.
-
the rarely used Conditional
operator, ?, which I will ignore.
-
Hour Seven's workshop
illustrates the use of the switch statement to create mechanism
for user input. Various text strings typed by the user in response
to the prompt function are categorized by the switch statement.
SAQ:
Code an equivalent to Listing 7.4 that uses nested if-else
statements instead of a switch
statement. (
This should be easy for anyone who has taken COSC 200; if you havent' simply
look at the answer to see an example of the difference between the if-else
and switch constructs.)
8.
Repeating Yourself; Using Loops (
Supplements
Moncur Hour 8.):
-
This hour, along with Hour 7, is straightforward
because control structures are not associated with objects and therefore,
have no inconsistencies in terminology. In fact for those
who have experience with C, C++, or Java, already know everything in this
chapter because JavaScript, like those languages, uses ANSI standard C
syntax.
-
This hour extends coverage of structured
control structures with the iteration
(looping) constructs one of the two repetition constructs;
the second,
recursion,
is not covered in this hour. In fact, recursion is not presented
at all in Moncur as a distinct control structure, although is used in some
examples.
-
Repetition control structures are
based on Boolean expressions, just as selection control structures
are. (See Section 7.C,
above.)
-
Iteration control structures
repeat a "block" of instructions (delimited by "{" and "}"), governed
by a well defined Boolean condition or by an index the counts the number
of times a loop is executed. These two ways of governing a loop define
two fundamentally distinct categories:
-
Indefinite loops are governed by a "looping
condition", a Boolean expression. In JavaScript, loops execute while
their looping condition is true.
-
While
loops evaluate their looping condition at the beginning of the
loop; if the condition is true the body of the loop will be executed.
However, if the condition is initially false, the loop body will not execute
at all. (This is the primary destinction between a while loop and
a do...while loop.) If the condition is initially true,
the loop body will be executed over and over until something happens, within
the loop body, to change the looping condition to false; when the body
is finished the
-
Do...while
loops execute the instructions in the loop
body block once and then evaluates the looping condition (at the end of
the loop), repeating if it is true or exiting if it is false.
SAQ:
9a) What is the fundamental difference between a while loop and a do...while
loop? (b) Which is the most general?
-
Definite loops are governed by an index or counter.
-
For loopsfacilitate
counter-controlled loops by optionally (1) initializing the counter
(2) specifying the exit condition, and (3) specifying how the
counter changes. Although all of these are optional, for loops
typically contain all of these. Like the while
() loop the exit condition (usually
an maximum value of the counter) is evaluated at the beginning of the loop,
i.e. before the loop body is executed.
-
For...in loopsare
specifically designed to be used to repeat a specified operation
on all the properties of an object. This will become more
clear when we cover JavaScript's object models; Moncur
returns to this in Hour 16.
It is important to code an execute the for (i
in navigator)... example on Moncur, page 105.
-
Infinite loops occur when the loop body contains no
way to change the looping condition to false, i.e. the loop body is executed
"forever".
-
This can be a design decision, i.e. writing whiletrue
() {instruction of loop body} creates
a "loop forever" if the loop needs to be run continuously until an application
is closed. In other situations a break instruction (See the next
section.) can be used to execute
-
JavaScript has two instruction that can alter the execution
sequence of the loop body.
-
The break instruction can be used to "break
out of" a loop body (or any block of instructions). This makes it
possible to discontinue the execution of the loop body and go immediately
to the first instruction after the end of the loop construct. This
can be done anywhere within the the loop body and/or at several
different points within that body.
SAQ:
Under what conditions would an infinite loop with a break
statement be preferred to a pure while
loop or pure do...while
loop (i.e. loops without break
statements)?
-
The continue instruction allows the developer
to set a condition under which the execution of the loop body can be aborted
and starte over.
-
Two constructs, normally assoicated with repetition,
are not covered in Moncur, Hour 8:
-
recursion, mention in section 8.B, above.
-
the with statement which is used to specify
a default object to be associated with a block of statements. Moncur
discusses the with statement when he introduces objects in Hour
9.
-
Hour Eight's workshop
is a good, useful example of JavaScript. It illustrates how a script
can prompt the user for imput and then respond to that input; this is a
task that is used very frequently, so it is work studying this example
carefully.
SAQ:
Why was an indefinite loop used for the input part of Listing
8.7 and a definite loop used for the outpart
part?
MOVING
ON TO ADVANCED JAVASCRIPT FEATURES: (Moncur, Part
III):
9.
Using Built-In Objects(
Supplements
Moncur Hour 9):
-
Unfortunately
JavaScript
uses some terms for object oriented features that differs from standard
OO terminology. To avoid confusion, refer
to the comments
in the study guide about inconsistencies in OO terminology. This
applies
to all the "Hours" of Moncur's Part III, i.e. hours 9, 10, 11, and
12, below.)
-
The "bottom line" is that, to relate
the object based JavaScript, to OOPL
-
think of JavaScript "objects"
as either:
-
"abstract" objects (equivalent
to OOPL/UML "classes") or
-
"real" objects, i.e. instances
of "abstract" objects (equivalent to C++ "objects" which are
instances
of C++ "classes").
-
think of JavaScript "properties"
as
OOPL/UML "attributes".
-
This is essential for those who have
used C++ or Java or for those who plan to learn these languages at FSU,
where C++ is the language of choice in COSC 200 and COSC 201. It
is less important for those who have never programmed before and are only
interested in using JavaScript as a "tool" to enliven their Web pages.
-
See the study
guide for Hour 9 for more discussion of this problem.
-
What is an object (
in
JavaScript)? This question, when posed in Moncur,
refers to JavaScript, not other OOPL.
-
JavaScript objects (classes) are software constructs
that encapsulate:
-
properties (attributes) which specify the state of
the object. An instance of the object has particular values
defined for every property.
-
methods which specify the behavior of the object.
Properties (attributes) and methods are often collectively
called object "elements".
-
Abstract JavaScript objects are all built-in, i.e.
are part of the language. The developer can use these built-in "abstract"
objects (classes) in scripts or functions by instantiating them, i.e. making
them "real" objects when displayed by a browser.
-
JavaScript, unlike OOPL, can not create new objects (classes).
This is what prevents it from being an object oriented language, i.e. the
essential feature of all OOPL is the "class" construct, the ability
to encapsulate state (attributes) and behavior (methods) within self-contained
classes. The creation of classes and relating them to each other,
in an object oriented software "architecture", is the essence of object
oriented software development. This is beyond the scope of JavaScript.
-
The built-in objects of JavaScript are equivalent to the
class libraries of Java (called the "Core Java API"), C++, etc.
Therefore, the use of JavaScript objects, e.g. the core
JavaScript object model and the document
object models (DOMs), are entirely equivalent to using the class
libraries to create real objects in Java or C++ software.
-
"Real" JavaScript objects are created by instantiating
"abstract" JavaScript objects of the core object model or DOMs.
The syntax used is:
real object = newabstract object;
for example, from Moncur p 114, myname = new String("Figby");
where myname is a real
object () and String
is the abstract object ()
instantiated by this declaration. This syntax and example use the
simplified
syntax allowed in JavaScript; a more rigorous form (that is equivalent
to instantiation in Java and C++) is given in section
5.A of Appendix A.
-
Using the with Keyword:
with is a term used to simplify coding Javascript. It is used to
specify an object that is used within a block of statements, i.e. the properties
(attributes) and methods in the with block are assumed to be those of the
specified object. See Moncur's example on
page 115 and Appendix
A, section 4.
-
The Math Object (See Moncur,
Appendix D and Appendix
A, section 5.E.):
-
JavaScript's Math object, like all
JavaScript object, is built-in; it is part of the core
JavaScript object model.
-
The Math object is not an abstract object
because it can not be instantiated, i.e. a new object, of "math
type" can not be created. The object is used exclusively
to perform simple math operations such as trigonometric, logarithmic,
statistical, etc.
-
The Math object has eight properties which
are numerical constants:
-
none are covered in Hour 9.
-
All eight are covered in Moncur,
Appendix D.
-
five provide constants associated with logarithms (E, LN2,
LN10, LOG2E, and LOG10E.
-
one, circle constant, PI, and
-
two square root constants (of 2 and 1/2).
These are specified, in JavaScript code, by writing Math.propertyName().
-
Methods of the JavaScript Math object:
-
The Math object has, according to Wilton, has 17
methods, all of which are in ECMA 262.
-
six trigonometry methods (sin(x),
cos(x), tan(x), asin(x), acos(x), and atan(x) ())
that return the trigonometric values of their argument, x.
-
two logarithmic methods (exp(), and log())
that return ex ()
and natural logarithm().
of the argument, x, respectively.
-
two statistical methods (max(x,y), and
min(x,y)) that return the maximum ()
and minimum (). of the
arguments, x and y.
-
four float to integer conversion methods (round(x),
abs(x), ceil(x), and floor(x)) that
-
two exponential methods (pow(x), and
sqrt(x)) that return the power ()
and square root (). of
the argument, x.
-
one random number generating method, random(x),
that returns a random number between 0 and
1().
These are specified, in JavaScript code, by writing Math.methodName().
-
Four methods (ceil(x), floor(x), round(x) and random(x))
are covered in Hour 9.
-
All 17 are covered in Moncur,
Appendix D.
-
The Date Object (See Moncur,
Appendix D and Appendix
A, section 5.E.):
-
JavaScript's Date object, also part of the
core
JavaScript object model, provides developers with built in tools,
assoicated with the host computer's clock, that can manipulate things
associated with times and dates.
-
The Date object has only two properties,
it's constructor and prototype
which returns the prototype of the object, used to extend the object's
interface.
-
The methods of the Date object may be used to set,
get, and convert dates and times. The Date object has, according
to Wilton, has 44 methods (42 of which are in ECMA 262), but Moncur covers
only 19 of them.
-
Nineteen are covered in Hour
9.
-
seven "set" methods (setTime(), setDate(),
setSeconds(), setMinutes(), setHours(), setMonth(), and setFullYear())that
specify a time or date
-
eight "get" methods (getTime(),
getDate(), getSeconds(), getMinutes(), getHours(), getMonth(), getFullYear()
and getTimezoneOffset() ()) that retrieve the
current time, date, and time zone difference.
-
four "convert" methods (parse(), UTC(),
toGMTString(), and toLocaleString()) that change between
the various formats of time, date, and time zone (compared to the UTC (GMT)
standard).
-
The same nineteen are collectively itemized in Moncur,
Appendix D.
-
ECMA 262 Methods not covered in Moncur include:
-
nine additional "set" methods (setMilliseconds(),
setYear(), setUTCDate(), setUTCMilliseconds(), setUTCSeconds(), setUTCMinutes(),
setUTCHours(), setUTCMonth(), and setUTCFullYear())
-
eleven additional "get" methods (getDay(), getUTCDay(),
and the "get" equivalent of the preceding "set" methods.)
-
three additional "convert" methods (toSource(),
toString(), and ValueOf()).
-
Hour Nine's workshop
is a useful exercise to test JavaScript's random number generator, but
it doesn't really require the use of the other methods.
10. Working with the
Document Object Model(
Supplements
Moncur Hour 10.):
-
Moncur Hour 10 introduces
a very limited subset of JavaScript's implementation of the W3C standard
"document object model" (DOM) which represents
every HTML element as an object, thus allowing programming languages to
access the elements and manipulate them. In this case, of course,
we will use the DOM as the means for JavaScript to access Web page elements.
This technique allows Web developers to treate
any Web page element (window, frame, link, graphic, etc.) as an object
and to manipulate such objects with JavaScript.
-
Understanding the Document Object
Model (DOM)
introduces the DOM, a hierarchically related collection of abstract
objects, that are object
oriented "components" that are special cases of the
class libraries of OOPL. Unfortunately because there are many versions
of the DOM and inconsistencies in terminology this is one of the most confusing
subjects in JavaScript.
-
To distinguish
between various types of DOMs I have defined a
simple terminology in Appendix A; I will focus on the browser
independent version of the DOM, that I call DOM/BI.
-
Diagrams
of the DOM are given in many texts, but they are seldom accurately
described, i.e. the relationships between
DOM objects, represented by the diagram's lines between the objects, are
not discussed much less defined.
I think this is inexcusable (After all Confucius said "...a picture is
worth a thousand words...") because the lines do not all represent the
same kind of relationship between objects.
-
Compare my PLATFORM
INDEPENDENT W3C DOCUMENT OBJECT MODEL (W3C DOM)
to Figure 10.1 in Moncur
(which is typical of DOM diagrams in JavaScript texts).
-
The major differences is that I
label the relationships "Has-A" (the OOPL "aggregation") and "Is-A" (the
OOPL "inheritatnce" or "generalization"). I believe it is essential
to distinguish these. From a practical point of view, you
can think that, with the exception of the frames object, the
lines between most objects represent aggregation
which can be viewed as "containership"
of the lower level object within the parent. For example a window
object contains (or has-a) document object. (Note that frames
has an is-a relationship with the window object, but the window
object can also have a has-a relationship with frames objects.)
-
Moncur
uses the "parent and child" description
of object relationships in a DOM (used
in many JavaScript texts). 
If you think about it, this is obscure, if not meaningless!
He doesn't descibe this term anywhere (that I can remember), but, obviously,
parent objects do NOT "give birth to" child objects. Instead higher
level objects "can" contain lower level objects. (In OOPL
texts the term "superclass" and "subclass" are used so perhaps one could
use "superobject" and "subobject", but I have never encountered these terms.)
-
A second difference is that my diagram
contains all the W3C standard objects of the first three levels, but
Moncur's
omits the objects Frames and Navigator (covered elsewhere).
That is an acceptable approach in a user-friendly presentation like Moncur,
but I think the omissions should, at least, be mentined.
-
Like
all abstract objects, DOM objects are OO constructs that encapsulate
the object's "elements()",
i.e. properties (attributes)()
that describe the object state and methods()
that describe the object behavior represented by operations on the state
of the object.
-
The History
of the DOM has been an evolution of rival
implementations. Netscape invented JavaScript; Microsoft stole the
idea and modified it to suit Windows; and both Netscape and Microsoft developed
competing DOMs.
-
Fortunately all DOMs support, in
a consistent way, a basic DOM that I call "Browser
Independent DOM" or "DOM/BIC". This is all that is covered
in this Hour. (Specifically we present the DOM
levels 0, 1, and 2.) The platform
specific DOMs are covered, in a minimal way, later.
-
Using window
Objects introduces the DOM/BI's
window object. the highest level object of all browser
oriented DOMs, i.e. the one that can contain all lower level objects.
Note that since a frames[] object is-a window object,
everthing that applies to windows applies to frames.
-
Working with Web Documents
introduces the DOM/BI's
document object., the most used object in the DOM. The
object refers to the HTML page()
displayed in the current browser
window().
-
Getting Information About the Document
covers two Internet address properties (URL and referrer)
and two document information properties (title and lastModified).
-
Writing Text in a Document
introduces the very useful output methods write and writeln.
SAQ:
What output methods are available that are not associated with document,
i.e. do not output to a specified location in the HTML document?
-
Clearing an Rewriting Documents
explains how the open and close methods can be used to
allow output from write and writeln to be changed without
actually closing the browser window. (Note that window.open
and window.close actually open and close a browser window, BUT
document.open
and document.close do NOT open and close a document. Instead
the document is cleared and rewritten "on the fly" by write and
writeln methods.
-
The rewritten document is not displayed
until a document.close is executed.
-
The document.open instruction
can specify a MIME document
which makes it possible to open any MIME file, e.g. an image or files of
plug-in applications.
-
Using Links and Anchorsintroduces
the array basics of the HTML link mechanism with the abstract
links[]
and anchors[]
objects.
-
The links[] and anchors[]
objects contain all hyperlinks and targets in the current HTML document.
-
links are abstract location
objects so they have
all their members.
-
the length property of all arrays give
the number of elements in that array.
-
Accessing Browser History
introduces the DOM/BI's
history object.
-
Moncur is referring to the NN/4 DOM
when he list the current, next, and previous properties;
current
is the only property that is the same in NN/4 and IE/5.
-
Working with the location
Object introduces the DOM/BI's
location object
-
Readin Information about the Browser
introduces the DOM/NN4's navigator object that represents
the browser version being used. This is not part of the ECMA specification,
and, therefore, is not included in Appendix A. It is essential
for writing browser independent JavaScript, i.e. after detecting the browser
version, scripts can select different blocks of code for different browsers.
-
Hour Ten's workshop
is an exercise on using the DOM/BI's history object to
create Back and Forward buttons in on a Web page.
11. Creating
Custom Objects (
Supplements
Moncur Hour 11.):
Currently
being created!
-
In Hour 11, Moncur
covers JavaScript's object creation facility, a restricted analog
of the OOP class definition feature which is limited to encapsulation.
This means that
-
properties (attributes) and methods CAN be encapsulated
within abstract objects (classes),
-
properties CAN be declared to have a type that is another
abstract object; this implements the "aggregation" (i.e. has-a())
relationship, and
-
methods CAN use abstract objects as:
-
arguments of of methods
-
the return type of methods
These implement the "dependency" (i.e.
uses-a())
relationship
between abstract objects, i.e. the abstract object that has such a method
"depends on" the abstract objects used as arguments or as the return value
of that method.
However,
there is an important OOPL facility, "access control",
associated with encapsulation, that are not available in JavaScript:
-
In JavaScript, a user-defined abstract object CANNOT
inherit the members of another object, i.e. JavaScript can not implement
the inheritance or generalization (i.e. is-a())
relationship.
-
Access to an abstract object's members
can not be controlled by the developer (a defining characteristic of
OOPL). For example, in an OOPL, a member that is defined to be "private"
can not be used outside the class, but, in JavaScript, this can not be
done; any object member can be used in scripts, functions, or other abstract
objects.
This means that JavaScript is an
object
based() language but NOT an object
oriented() language.
Note that many texts say that JavaScript can not implement Inheritance,
THE essential feature of OOP. (Moncur doesn't even mention inheritance.)
This is NOT true; in fact
-
Inheritance is implemented in the
built-in abstract objects of the DOM, presented in the preceding Hour,
where, for example, the frames[] object is-a window()
object, the images[] object is-a array[
]() object, etc.
-
User-defined
inheritance can be implemente with the prototype property
or the core object
object.
This is covered in Appendix A, section . To see how this works,
view this simplified example.
SAQ
(for COSC 200 veterans): What are the (a) similarities and (b) differences
between abstract object creation in JavaScript and class creation in C++?
-
Using (abstract)
Objects to Simplify Scripting
-
Defining an (abstract)
Object is accomplished by defining a
constructor function with the name of the object. (See Developer
Defined Objects in Appendix A.) It should be noted that constructors
are a fundamental construct in all OOPL. However, constructor
facilities in most OOPL are much more sophisticated than the rudimentary
JavaScript constructor function, e.g. there are default constructors
(which means that a constructor need not be explicitly defined) and user-defined
constructors are much simpler than in JavaScript (where they must contain
the definition of every member).
-
Note that a "real" object can be
created by instantiating the built-in object object.
I call this the creation of a "real" object because creation and instantiating
are combined. See Appendix
A, section 5.G.a.
-
The constructor, in JavaScript,
must contain all the properties and methods of the abstract object.
In OOPL, the constructor is a method of the class. In fact the JavaScript
constructor is actually equivalent to the class definition of OOPL,
i.e. the construct where all the attributes and methods are defined.
This
is another inconsistency to add to the confusing differences of OOPL, but
don't worry to much about it. Just think of the JavaScript constructor
as the abstract object definition, equivalent to the class definition in
OOPL.
-
Defining an (abstract)
Method, in JavaScript, is more clumbsy
than in OOPL. Encapsulation of a method within a JavaScript object
(real or abstract) is a two step process:
-
define a function
-
encapsulate the function within
the object constructor by assigning that function to a method.
See Appendix
A, section 5.G.b.i for an example.
-
Creating an Object Instance
explains how a "real" object is created from an "abstract" object by instantiating
that abstract object. This is accomplished by the instruction
realObjectName =
new abstractObjectName;
-
Customizing Built-In (abstract)
Objects is a rather innocent looking introduction
to "adding a method to an abstract object". (See the title to Listing
11.2 in Moncur.), but it opens up
the complex subject of JavaScript's object object and the not-well-know
facility of inheritance in JavaScript (provided via the prototype
property of object; see Listing
11.2 in Moncur.). (
I
honestly don't know if Moncur
even knows this exists, because he makes no mention of inheritance.
I'll be charitable and assume that he decided to avoid the complex issue.)
-
What Moncur does in instruction
13, of Listing 11.2 is add a user defined
function to the built-in abstract object String of JavaScript. This
effectively "extends the definition of String" by creating a new
method (Remember that functions that are part of an object are called methods,
so when we "add" a function to an abstract object it becomes a method.)
In
OOPL terminology, extending a class implements inheritance.
-
example A
SIMPLE JAVASCRIPT INHERITANCE EXAMPLE.
-
Hour Eleven's workshop
extends the "business card" example developed during the Hour by adding
a method PrintCard to the user-defined abstract object Card.
12. Responding
to Events (
Supplements
Moncur Hour 12.):
-
Hour 12, Moncur
introduces the JavaScript Event Model which allows
the Web user to interact with the JavaScript embedded within an HTML document.
-
Understanding Event Handlers
introduces the remarkably simple JavaScript Event Model as a simple
way to make HTML documents interactive. The JavaScript terms
that respond to events are called "event handlers"; Moncur focuses
on mouse and keyboard events.
-
objects and Events
-
Each event is associated with a DOM
object.
-
An event has a unique name,
and an associated eventhandler. that is built into the language.
To
define an event handler, one concatenates "on" to the beginning of the
event name. e.g. the event mouseOver has a associated event
handler onMouseOver()that
is built into the language.
Moncurmakes
a careless mistake, on page 150, when he calls "onMouseOver" an event;
don't let this confuse you.
-
Creating an Event Handler
shows how an event
handler is used as an HTML tag attribute to make the tag respond
to an event by either
-
assigning a sequence of statements
to the event handler or
-
assigning a previously defined function
to the event handler.

However
Moncur neglects to mention that an event handler can also be defined as
an abstract object's property (attribute).
-
Changing Event Handlers with
javaScript describes the most fundamental
way of associating a function with an event handler i.e. by using
the event handler property of an object. It is a way of associating
a developer-defined function with a particular event handler of an object.
Moncur's example
Function mousealert(){
alert("You clicked
the mouse!");
}
document.onMouseDown
= mouseAlert;
can "change" the onMouseDown
event handler of the document object, but only if it had
already been defined. However, the same syntax can be used for an
unspecified event handler, in which case, it "creates" that event handler.
-
Using the event Object
introduces
the built-in DOM object that defines all events for a particular
browser, i.e. each event sends an event object to the event
handler, which receives the event object as a parameter. However,
Moncur uses the Netscape Navigator 4.0. Of the properties listed
my Moncur,
-
only type (the kind of event,
e.g. mouseOver) and screeX and screenY (cursor location
coordinate on the monitor) are platform independent.
-
target, which modifiers, data, pageX,
PageY, layerX and layerY are
-
Using Mouse Events
(See the table of Commonly
Used, Platform Independent JavaScript Events):
-
Over and Out:mouse
movement can be responded to, in JavaScript,
by using three event handlers:
-
onMouseOveris
called when the cursor is moved over an object displayed by a browser.
-
onMouseOut is
called when the cursor is moved out of the borders of a displayed
object.
-
onMouseMove
is called when the cursor is moved; however, because this is so
common, this handler is not available by default; event capturing (
beyond
the scope of this introductory presentation) must be used.
-
Ups and Downs
discusses what happens when a mouse button is clicked. The particular
mouse button may be specified by the which property of the event
object; 1 for the left button or 3 for the right button.
-
onClick (or
onDblClick
)is called when the a mouse button is clicked (or double clicked)
while over the object containing the event handler.
-
onMouseDown
and onMouseUp represent
the two halves of onClick;
these give you more control over the clicking response.
-
Using Keyboard Events
shows how the developer can control what happens when the user uses the
keyboard.
-
onKeyPress
is called when a designated key is held down.
-
onKeyDown
is called when a designated key is hit.
-
onKeyUp
is called when a designated key is released.
-
Page Events (Moncur's Using
the onLoad Event) give
the developer control of what happens when the page in current browser
window is opened or closed or an error occurs.
-
onLoad
is called when a document or multimedia file is displayed or presented
by a browser.
-
onUnoad
is called when a document or multimedia file is unloaded from the browser
display.
-
onError
is called when an error occurs when a document or multimedia file is loaded
by a browser
-
Hour Twelve's workshop
covers how the developer can cause a message to be displayed in the
browser status line (at the bottom of the browser window) when the
cursor moves over a page element. This is an effective way to annotate
links or add prompts. {}
WORKING
WITH WEB PAGES (Moncur, Part IV):
13. Using Windows and Frames(
Supplements
Moncur Hour 13):
-
Hour 13, Moncur
introduces JavaScripts facilities for manipulating Web page elements that
are covered throughout Part IV;
this hour focuses on Windows and Frames. In particular, the
hour covers:
-
creating a window,
-
opening and closing windows,
-
delaying statement executions using the setTimeout method of the
abstract
object window,
-
displaying dialog boxes, and
-
manipulating HTML frames.
-
Controlling Windows with Objects
takes a closer look at the DOM (actually what I call the "DOM/BI",
introduced in Hour 10), in particular the
abstract
object window. which, when instantiated, produces a real
window in the browser display. The real window always
refers to the window currently displayed by the browser; theselfkeyword
is a synonym for the current window.
-
Creating a New Window
is accomplished by calling the method open() of the window()
object with the statement window.open().
WindowObject = window.open("URL",
"window name", "property list separated by commas")
where, as usual, the italicized
words must be replaced by developer-defined words, in this case arguments
of the open() method, i.e. discriptive names, used in our example,
that must be replaced with actual values in real code, e.g. URL
might be "cnet.com" and window name might be "myWindow".
Note that you must give the new window you open a name because you
need to reference the window, by name, in order to manipulate it, e.g.
to close the window; see the syntax of the method in the next section.
-
NOTE:
Moncur uses inconsistent terminology again here;
he calls the property list "features"
which is misleading; the correct term is "properties", which specify
the state of the window object (In OOPL like Java and C++ these would be
called "attributes".).
-
The most interesting capability of
the open() method is the ability to customize the appearance
of the opened windows by specifying its size, whether or not it has
various menus; these, as Moncur says, can be "floating windows" that look
nothing like a typical browser window.
-
See the examples
in Moncur; they are good ones.
-
Opening and closing Windows
-
A window is closed by calling the method
close()
of the window
object with the statement myWindow.close(), where
my window is the name of the window being closed. (Note that this
syntax is NOT consistent with the open() method syntax,
i.e. you do NOT write window.close(myWindow)!)
-
Comments about Moncur,
Listing 13.1:
-
This listing has NO script! The
JavaScript is all contained in event handlers, within HTML tags.
-
Lines 10-14 are all one HTML tag which contains two JavaScript
onclick
event handlers.
-
The empty quote (' ') argument of of
open() means not URL so a blank window is opened.