-
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.
- I will be adding SAQs as I develop this appendix,
but the hints and answers to these won't be published until I finalize their
numbering sequence.
- ADD I/O via document object in sections
1.D.c.vii.2 and 6, i.e. since CSJS is embedded in HTML, document.write()
and alert() (include javascript:alert(document property)
tip) to provide output, confirm()to allow confirmation, and prompt()
provides interactive input.
- DONE:
{Add Tree graphic e.g. (?)
Window(DOCUMENT(anchor, forms, images, links), FRAMES, LOCATION, NAVIGATOR(appName,
appVersion))}
-
Drafted: 4/26/00; (major rewrite) 3/20/01, 4/14/01;
10/26/02
Currently being expanded!
COSC 330
APPENDIX A TO LM
330-VII
THE JAVASCRIPT LANGUAGE
This appendix is intended to serve a concise
presentation of JavaScript, as a programming language.
It should complement the user-friendly, but rather ad hoc, presentation of
Javascript in Moncur (which is paralleled by LM VII). This appendix does
not attempt to cover every aspect of JavaScript; instead, it presents those
aspects of JavaScript that are the most useful constructs of the language,
in particulare those that are client side and browser independent.
By far the most common use of JavaScript is "Client-Side JavaScript" (CSJS)
which refers to JavaScript code that is embedded within HTML documents and,
consequently, executed by a browser (the client). (Server-Side JavaScript,
SSJS, the other form, is less common and will only be briefly discussed at
the end of this Appendix.) Furthermore, this Appendix focuses on JavaScript
that is browser independent; a brief overview of the browser-specific language
versions is also given at the end of the appendix.
The Objectives
of this appendix are to:
- supplement LM 330 VII with a systematic reference to JavaScript,
analyzed according to its programming language construcrts
- serve as a concise presentation focused
on
-
Client-Side JavaScript (CSJS)
- the browser-independent constructs
of CSJS
- serve as an overview of JavaScript
for computer science students who are familiar with C++ or Java
- serve as a review of JavaScript in
a memorable format.
TPQ 1: Rewrite the preceding objectives in terms of personal accomplishments
to be attained after finishing the study of this learning module.
The sequence of presentations
in this learning module is as follows. { distinction of core
JS} You can click
on any link to jump directly to that section
- OVERVIEW OF
JAVASCRIPT
- CORE JAVASCRIPT BASICS
- CORE JAVASCRIPT DEVELOPER-DEFINED
FUNCTIONS
- CORE JAVASCRIPT
CONTROL STRUCTURES
- Selection Constructs, if-else and switch
- Repetition Constructs, Definite Iteration,
Indefinite Iteration, and Recursion.
- CORE JAVASCRIPT OBJECT
MODEL
-
CSJS DOCUMENT
OBJECT MODEL (DOM), BROWSER INDEPENDENT CONSTRUCTS
- CSJS EVENT MODEL, BROWSER INDEPENDENT
CONSTRUCTS
- CSJS
DOCUMENT OBJECT MODELS, BROWSER SPECIFIC CONSTRUCTS
- Netscpe Navigator Object Model
- Internet Explorer Object Model
- OVERVIEW OF SERVER SIDE JAVASCRIPT
- SUMMARY
1. OVERVIEW OF JAVASCRIPT
CONSTRUCTS (Use S,C, D, &Q ?):
to distinguish
"generic JavaScript code" that must be written by the programmer, I will use italics, fixed width text,
e.g. "list of statements" would mean that a list of JavaScript statements,
each ending with a semicolon, would have to replace these words in actual
JavaScript code. See, for example, the code syntax in section 1.D.a.
- JavaScript
is a very high level, object based, scripting language that was originally
designed specifically to provide interactivity and animation to Web
pages. Review the overview
of JavaScript in LM VI.
- JavaScript is a very
high level language (VHLL) because it was specifically designed for a limited area of application. i.e. to be
embedded within HTML documents. (Remember that VHLL are special purpose languages
that are very powerful in their limited domain of application whereas HLL
(high level languages) like Java and C++ are general purpose languages that
can be used in any kind of application.) It was conceived to
write platform-independent, event driven scripts that provide interactivity
and animation, not available HTML(1), e.g. dynamic Web page
elements, interactive multimedia, forms, simple web databases, etc.
- JavaScript is "object based"
(as opposed to "object oriented") because it only provides a very limited
set of object oriented facilities. (Review the differences between
JavaScript and OOPL as explained in the Study Guide to LM VII.) ...
Currently, Javascript does not support the following OOPL features:
- data types,
- access control via the private, protected, package, and public modifiers
of Java,
- inheritance/generalization, or
- abstract classes or interfaces (which require inheritance).
Note that the standard specification of JavaScript is being upgraded so it
may accomodate traditional class features in the future. - JavaScript is a scripting language
because it is designed to augment another language (HTML) rather than
be used to create stand-alone applications. Client-side JavaScripts
scripts are normally embedded within HTML documents.
It is very important to realize that,
being a scripting language, JavaScript's developer interface (the way
it "looks" to the person writing the scripts) is very different than most
other programming languages. (See section C,
below.)
- Core JavaScript, the base
JavaScript language, which contains all the language primatives (keywords,
operators, control structures, functions, and built-objects) of the basic
language. This has been accepted as an international standard in ECMA-262 specification of ECMAScript.
The current (third) version is based on JavaScript 1.1; however, work on
this standard is continuing.
- Client-Side JavaScript
(CSJS) is composed of core JavaScript and many additional client
objects that are designed to be embedded within HTML documents.
These enable the manipulation of such documents (e.g. adding dynamic effects,
checking and submitting data via forms, etc.) as well as the browser itself
(e.g. directing the browser to load other HTML pages, display messages, etc.).
Unfortunately CSJS is not completely platform-independent because Microsoft
has ignored standards when it implemented its version of the language, called
"JScript"; therefore, the object models of Netscape and Microsoft are not
completely compatible. However, in this course (and consequently
in LMVII and this appendix), only the constructs of Java that are browser-independent
are covered and none of the assignments require broswer-specific Javascript.
(
In fact, students are strongly encouraged
to write scripts that are broswer independent, unless there is a compelling
reason not to do this.) The complete
CSJS object model is presented in a Adobe Acrobat document accessable
from the article "Danny
Goodman's JavaScript Object Roadmap and Compatibility Guide."
- Server-Side JavaScript
(SSJS) is composed of core JavaScript and additional server objects
that enable access to file systems, databases, etc. on servers in a distributed
computer system. It's used
to create and/or customize server-based applications by scripting the interaction
between objects. The SSJS object model for the Netscape Enterprise
Server is detailed in the View Source article "Server-Side
JavaScript Object Roadmap and Compatibility Guide."
Since SSJS is an advanced use of JavaScript
that is not useful in typical Web site maintenance, it will not be covered
in this course.
Core
JavaScript contains language constructs and built-in objects that are applicable
to both clients and servers so if you know core JavaScript(2), you can write CSJA and SSJS, but to take full advantages
of these, you will need to learn the extensions to the core language.
In COSC 330 we will be primarily concerned
with Core JavaScript and the browser-independent constructs of CSJS. For more information on the distinction
of these three components of JavaScript see the excellent artical,
All About JavaScript by Robert
W. Husted at http://developer.netscape.com/viewsource/husted_js/husted_js.html
-
The termanology of JavaScript overlaps that of other languages (especially C, C++(3), and Java) but, unfortunately, there are confusing inconsistencies between these languages.
-
Unfortunately JavaScript uses the word "object" in two
distinct contexts. (In fact,
"object" is probably the most misused
term in object oriented programming, so
its misuse is not limited to JavaScript!) The most traditional use
of "object", in object oriented programming languages (OOPL), is to
use it to refer to an instance (a real, unique quantity) of a class (an
abstract OOPL construct that is a "template" for instances). For
example, in an OOPL like Java, a specific point (e.g. origin) on a computer screen with values for
x and y (e.g. x=0, y=0) is a unique object, but it is an instance
(4) of the class Point
(an abstract "template" which has the attributes x and y and may have
methods like move(x,y)). In Java, an object is created when an instance
of Point (5) is created
using the keyword "new".
origin = new Point(0,0); //In Java origin is an object, i.e. an instance of the
class Point
- The origin of this inconsistency is the fact that JavaScript does NOT have the word "class"; it uses the word "object" instead of "class".
- In order to be consistent with OOP terminology,
JavaScript "objects" that are built into the core JavaScript language
should really be called "classes" because they are abstract quantaties,
from which real objects must be instantiated. The simplest guideline
is to recognize that the word to the right of the keyword new is, in OOPL, a class, not an object,
but, in JavaScript, it is also referred to as an object. (The word
to the left of the = new is an object (instance).) For
example,
myBirthday = new Date("9
April 1940");
myBirthday is an object
(instance) but in true OOPL termanilogy, Date is a class (called
an object in JavaScript). See the Study Guide of LM
VII, section 3.2.1.1. - However, the built
in "objects" of the core object model (COM) and document object model (DOM)
can be true objects (instances), e.g. the object document is actually the current page (i.e.
document.write() will output to the page being displayed)
and frames, images, etc. can exist. However, although it is usually
consistent with OOP termanilogy to refer to "objects of the DOM" or "objects
of the DOM", one must be sure that the "object" you are considering actually
exists; if you are referring to an abstract construct it should be thought
of as a class (6).
- It is probably "safer", for object oriented programmers, to think
of the COM and DOM as a library of classes that complement the JavaScript
language like the class libraries associated with C++ and Java complement
those languages.
-
NOTES;
- I will not belabor this point, but this inconsistent terminology
can confuse you when trying to draw anologies with other OOPL, so
be careful. If this seems confusing at this point, discuss it
in class, and come back to this when you study the "objects" of the CORE JavaScript
and theand .
-
In order to avoid confusion, in the following presentation, I
will replace the word "object" in JavaScript with "abstract objects" and "real objects" to distinguish "classes"
and "instancese" in JavaScript code.
-
The "data", in JavaScript, that specifies the state
of running program is referred to as "properties". These are
more properly referred to as attributes or variables in the UML (Unified
Modeling Language), the international standard for object oriented language
specifications. (To be accurate there is a subtle distinction between attributes
and variables in object technology, but this is beyond the scope of
this course.) Unfortunately there is a lot of inconsistencies
in the corresponding termanology in other languages; C++ uses "member data",
Java uses "fields", and component technologies (like JavaBeans) uses
"properties", like JavaScript! So to avoid confusion, I will use
"properties" (as does
Moncur), but remember
"properties", "attributes", "variables", "fields", and "member data"
are, at the level of this course, synonyms.
- Behaviour, the other fundamental concept along with
state, is also specified by three terms, "operators", "methods",
and "functions". To be accurate, "methods" must be part of an object,
and "functions" are not, i.e. functions stand alone (something not
allowed in pure OOPL like Java).
There are also subtle
similarities and differences between how these terms (and another, "procedures")
are use in JavaScript and other languages, but COSC 330 students need not
be concerned about these.
An introductory
article/tutorial on JavaScript variables and operators is at: http://www.webdevelopersjournal.com/articles/jsintro1/js_begin1.html.
We will return to this reference again but you might want to preview it
now. -
It is important (especially for beginning software developers) to realize
that there is a big difference writing JavaScript and other types of software.
In particular, HTML is the vehicle by which data is input and
information returned; this distinguishes JavaScript (as well as other
scripting languages) from other programming languages. This is
best emphasized by considering the different kinds of input/output (I/O)
environments of different categories of programming languages:
- Applications are stand-alone
programs that must be compiled (converted, as a whole, into machine language
files, ending in ".exe" in the Windows environment) before they are executed.
- Programs (or "main functions"
in C++ ) have their I/O facilities built into the program itself.
- Pure OOPL have a separate
class that acts as a I/O interface to a software architecture composed
of other classes.
- Java applets are unusual
in that they are "hosted" by HTML documents that act as clients. The
applets are software that reside on the server, but they are downloaded
and automatically executed by the client and their I/O is presented within
an HTML document displayed by a browser.
- Client-side scripts, like
those in JavaScript, are unique in that they (unlike server-side applets) are embedded within
an HTML document itself on the client. The I/O is really carried
out by the HTML, e.g.
- input is accomplished
via parameters, passed in an HTML tag, to the JavaScript or, interactively,
via HTML forms;
- output is displayed in
the HTML document itself, or in pop-up alert, confirmation, or prompt boxes,
or in the message bar, etc.
Therefore students who have taken couses using C++ or Java
(or who plan to take them), must realize that although the code generated
in these languages is often identical, the environment in which the code
is "run" is very different!The
most significant difference is that client-side JavaScript (like all client-side
scripting languages) is embedded within another language (in JavaScript's
case, HTML); therefore, the input and output to JavaScript is handled by
HTML whereas is Java and C++, I/O is part of the program itself.
In
practice this makes learning JavaScript simpler than learning most other programming
languages (where using the I/O facilities can have a significant learning
curve, shifting focus away from the programming to producing input/output).
- In general, JavaScript has three
manifestations:
-
- Since structured programming
is a subset of object based programming, JavaScripts implements all the
constructs of structured programming languages. (A structured programming language is one in which a program
is developed using structured control structures and blocks of
code or modules (procedures or functions) which can be coded without
detailed knowledge of the contents of other blocks/modules, thus allowing
a top-down design approach.) For a discussion of structure programming
see Software
Development, section 3 in LM IX of COSC 100. (To see structured
programming within the context of object-based and object-oriented languages
see "THE
EVOLUTION OF SOFTWARE DEVELOPMENT" in COSC 390, LM I.)
- Large
programs are broken down into smaller modules (the methods or functions (7) of
JavaScript).
- To make programs more readable,
- each
statement occupies only one line and
- blocks of code in selection or repetition constructs are
indented.
- JavaScript has
standard structured control structures of structured programing languages
and uses the same syntax for these as in C, C++, and Java. This
means that algorithms (the logical structure of methods and functions)
are defined in terms of three structured constructs:
- sequence,
the default execution is one instruction after another unless modified by
selection or repetition constructs,
- selection (IF-THE-ELSE) allows a logical expression to
select one of two alternative blocks of code to execute, (See the syntax
and example in Section
0.2.G.a.i below.)
- repetition (WHILE, or REPEAT-UNTIL loops or recursion)
allows a logical expression to govern the repetition of a block of code.
JavaScript utilizes only the WHILE loop.
An outstanding
article/tutorial on JavaScript control structures is at: http://www.webdevelopersjournal.com/articles/jsintro2/js_begin2.html.
We will return to this reference again but you might want to preview it
now.
- Structured languages and object oriented languages force the programmer
to write structured programs so 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.
- Java is
a scripting language (See LM
I, section 4.2.B.) which means that client-side (8) JavaScript code is
embedded within the HTML of a Web page and executed by the browser (9) as the HTML (10) is interpreted.
- A CSJS script is delimited by the script tag, i.e. the <script> tag precedes the script
code and the </script>
(11) tag terminates the 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
(12), only scripts within HTML documents.
(This is NOT true of SSJS where compiled JavaScript programs reside,
on their own, on servers.) An embedded CSJS script, with its script tag,
has the following syntax:
<script language="JavaScript
1.5">
<!--
//The JavaScript code
goes here.
//-->
</script>
- Note that the actual script
(the JavaScript code) would replace the comment "//The JavaScript
code goes here." the lines above and below this is HTML that
tells the browser that the tags enclose JavaScript, which must be passed
to the browser's JavaScript interpreter(13)to be executed.
- Scripts should be coded within
HTML comment fields (the <!-- 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.
- The language attribute
is optional, but should always be included for clarity. (
In JavaScript written for this course, you are required to specify the language
attribute.)
- JavaScript code, in separate
files, can be referenced by the src attribute, e.g. the
HTML
<script language="JavaScript"
src="FileScript.js">
</script>
imports the file FileScript.js
and executes it. A JavaScript file is simply a text file, ending
with the extension ".js", that contains JavaScript code.
- Any number of scripts may be embedded within an HTML document,
using multiple script tags.
- JavaScript terms define
the key concepts of the JavaScript language. JavaScript
code, like other programming languages, is made up of statements which direct
a browser to perform particular tasks. Key terms of JavaScript include:
- Constants and literals are containers
for data values that can not change
- Constants are values,
like pi, that can be used in mathematical expressions.
- Literals are constant
strings, i.e. text that can be used in phrases, but can not be changed.
- Variables which are containers
in which data values are stored, e.g. sum could contain a numeric value. (See
section 2.B,
below.)
- Operators which are used
to calculate or compare values, e.g. "+", "=", "<". etc/. (See section 2.C, below.)
- Functions are specific sets of statements (either built into JavaScript or user
defined) which perform a particular action; they are globally available
and can be "invoked" (called) by using the function name in a JavaScript
statement. A function may receive input via arguments
placed in parentheses following the function name, and it may return
an output value replacing the function name in the calling statement.
(See section 3, below.)
- Objects which are constructs that have a state,
specified by its "properties" (in JavaScript; in other languages these
are called "attributes".), and behavior, specified by the object's
methods. Objects are a fundamental
concept of JavaScript and are specified by JavaScript's various Object
Models (
equivalent to class libraries in C++). Scripts can written using built-in objects (
classes in Java/C++) that
come with JavaScript (i.e. the browser). See section 5 for a more complete description of JavaScript's object models.
(Also, review the inconsistencies
in OOPL terminology in the study guide, section
3.2.1.1.)
- Properties (
attributes (14) in Java/C++)are variables that are associated to their particular object,
i.e. they are specifically associated with the object where they are defined.
- Methods are functions
that are tied to their particular object (
classes (15) in Java/C++), i.e. they are specifically associated with the object
where they are defined. These are the "mini-programs", characteristic
of the object, that specify an objects behavior and can be called to modify
it's properties (change the object state).
- Expressions which
can be any combination of constants, variables, operators, function calls,
object properties, object method calls, or nested expressions that evaluate
to some result. These correspond to a clause (16) in
the English language. An expression is a group of symbols that
represent a value. Note that constants and variables are special
cases of expressions, so everything that applies to expressions applies
to constants and variables (but, not visa versa!).
SAQ : Justify the preceding statement that "constants and
variables are special cases of expressions".
- Statements are complete instructions that directs
the computer to perform a specified action. A statement consists of expressions (17), explained above, that are typiclly formed from assignments,
control structures, function calls, object manipulations, or comments.
As in English, a statement gramatically correct complete specification of
a distinct action, but, in programming languages, they are to be performed
by the computer.
-
JavaScript is very lenient about syntax, compared to many languages. While this may make
it more USER FRIENDLY, it can foster BAD
HABITS, so be careful. In particular, in most languages (C, C++, and Java, in particular)
you must end every statement (complete instruction) with a semicolon.
This allows the developer to format code any way desired because the compiler
or interpreter ignores spaces and carriage returns, i.e the computer ignores
your page layout so you are free to lay it out in the most human readable
way. However, JavaScript is unusual in that it will accept a carriage
return as an end of statement alternative to the semicolon; the only
time you must include a semicolon is when you have more than one statement
on a single line. Anyway, USING SEMICOLONS TO END EVERY LINE
IS A GOOD HABIT, especially for beginners who may sometime use other,
stricter languages, so add semicolons to all examples that (carelessly)
don't use them. Unfortunately, there are many of these in textbooks.
-
(premature; belongs in discussion of CORE DOC, but, for usability, should
be introduced earlier.
Here?). Include I/O via document object (ref.
to section 6, where core DOM is presented) i.e. since CSJS is embedded
in HTML, document.write() and alert() (include javascript:alert(document
property) tip) provide output, confirm()to allow confirmation,
and prompt() provides interactive input.
- Scripts which are small programs which,
in JavaScript, are specifically designed to be embedded within HTML documents.
They are made from all the preceding terms, i.e scripts consist of sequence
of statements modified by logical control structures, all delimited by the HTML <script> and </script>
tags..
SAQ : What is the (a) similarity and (b) difference (1)
between variables and properties, (2) between functions and properties, and
(3) between functions and methods?
2. CORE JAVASCRIPT
BASICS:
References:
Netscape's
Core JavaScipt Guide.
Netscape's
Core JavaScipt Reference.
- JavaScript, like all programming
languages, is based on a set of reserved words and symbols. which
can not be used, by the developer, in any way other than as defined in the
JavaScript language. Additionally there are other special identifiers
associated with the language that have specific meanings or are used in specific
ways and thus should not be used as names for developer-defined variables
or functions.
- There are 59 reserved words
that completely define the capabilities of the language. (The list of
JavaScript's reserved words is given in Appendix
B.)
- Unfortunately there is little
consistency between the vocabularies of different computer languages,
but JavaScript's reserved words are very similar to those of Java and, to
a lesser extent, C++.
However, it is important to note the
differences in reserved words and how they are used in different languages.
- Both Java and JavaScript have
59 reserved words but eight are different, the other 51 being identical.
- C++ has 48 reserved words, 35
of which are identical to JavaScript, but JavaScript has 24 reserved words
not in C++, and C++ has 13 reserved words not in JavaScript.
- There are 14 symbols
used individually or in combinations, as JavaScript operations (See section 2.D, below.)
- Variables in JavaScript:
- Variables (also called "identifiers") are the
containers (actually addresses in RAM) in which data values can be
stored or retrieved. Variables are accessed via their user-defined
name, which, in all languages, must conform to certain syntax constraints.
A JavaScript variable name, must
- begin with a letter or underscore ("_");
- followed by any combination of letters, digits (0-9),
and underscores.
- JavaScript is case sensitive, so the variables
Name and name are different.
- In JavaScript a variable must be declared as either
global or local, called the scope of the variable.
- A global variable is accessable
from any script on the page where it is defined.These are declared at the
beginning of a script.
- A local variable is only
accessable from within the function or method in which it was defined. These
are declared inside the function definition, before the function code.
- The syntax of declaring and initializing a variable
is
var variable name = initial value;
For example,var index=1; declares the variable
index as well as initializing its value to 1.
- Initialization is optional.
-
Variable declarations, in JavaScript
are optional. If they are omitted, they are declared by the interpreter
the first time they are encountered.
One should ALWAYS declare variables
in JavaScript to make the JavaScript clear;
in fact, in most OOPL, variable declarations are required, so doing in in
JavaScript fosters a "good habit".
-
Assignments: values are assigned to variables
using the syntax:
variable name = value;
where value can be a constant, an arithmetic
expression, or a function invocation, e.g.
SAQ: Give an example of the assignment of (a)
a constant, (b) an arithmetic expression, and (c) function invocation to
a variable x.
- Data types
in JavaScript (
Actually these datatypes are objects (classes
in other OPLL); however, discussion of this characteristic is deferred until
CORE JAVASCRIPT OBJECT .
In the following section we simply consider the practical aspects of these
data types.)
-
Unlike Java and C++, JavaScript is a weakly typed language.
This means that you do not have to specify the type of a variable in its
declaration and the value assigned to a variable, may any of
JavaScript's data types. JavaScript variables can have one of several
possible types.
- Numbers can be eiter integers, e.g. 7,
or floating point, e.g. 1.5.
- Integer values can have
any one of three types: decimal (base 10), octal (base 8), and hexadecimal
(base 16). Decimal integers simply consist of a sequence of integers.
Octal numbers are designated by a leading 0 (zero) followed
by a sequence of octal digits (0-&). Hexadecimal numbers are designated
by a leading 0x (or 0X) followed by hexadecimal digits (0-9, A, B, C, D,
E, or F).
- Floating point values represent
real numbers or fractions in one of two ways. Decimal numbers use the
standard decimal point. Scientific notation uses an "e" (uppercase
or lowercase) to represent an exponent ("ten to the power of") followed by
a signed integer specifying the power, e.g. 2.1e+2 represents 210. A
floating-point literal must have at least one digit and either a decimal point
or "e" (or "E").
- Boolean variables can have the values true
or false. Note that these Boolean values are different than in C/C++
where the integers 0 and 1 represent "true" and "false" respectively.
- Strings
represent text data, i.e. they contain "strings" of characters.
Built in indexing makes it possible to access individual characters
or substrings of a string. This makes it possible to process strings,
i.e. find, delete, incert, or replace characters or substrings. Strings
can also be combined using the overloaded "+" operator which concatenates
two strings, i.e. appends the second operand to the first. For example, the
statement word + "s"; would create the plural of word.
(Of course, selection constructs would have to be used to allow only those
words whose plural is a simple appended "s" to be processed this way.)
String literals are designated using a sequence of characters within quotation
marks or single quotes.
- Null means no value.
It is not the same as zero; a variable with a null value is empty.
Note: the preceeding types are,
in fact JavaScript objects, i.e. they have properties and built-methods for
accessing them. ....{EXPAND} - Conversion between data types:
- JavaScript data types are automatically
converted when variables of different types are processed together.
Typically any data type may be assigned to any variable, except one must be
careful with numbers. The behavior of some operators depends on the
type of data used, e.g. the "+" operator can operate on numbers as well as
strings, i.e.
"5" + "10" produces
"510" (string concatenation)
5 + 10 produces 15
(arithmetic sum)
- Conversions can be made explicitly,
e.g.
- parseInt() converts
a string to an integer value.
- parseFloat() converts
a string to an floating-point value.
- Operators
act on one or two operands returning a resultant value; the operands may be
expressions, variables, or constants. For example the '+' operator can add
two numbers to produce a third, or, if the operands are strings, it returns
the concatenated string. Operators can also be used to compare quantities
(expressions, variables, or constants), returning boolean values (true or
false). JavaScript's operators are identical to those in ANSI standard C
(and, therefore C++ and Java). These operators, given below, are divided
into categories for clarity.
- Arithmetic operators,
like those in all programming languages, take numerical values as operands
and return a single result. They include:
- the standard binary arithmetic
operators (+, -, *, /, and %) for addition, subtraction, multiplication, and
division, and modulus (remainder of division),
- uninary negation operator (the
minus sign preceding a negative number), and
- uninary increment and decrement
operators (++ and --).
SAQ: (a) How would one explicitly write out x++? (b) How
is this useful?
- JavaScript's binary comparison
operators (the same as ANSI C) are binary opertors that return boolean
values. They include == (equals to), != (not equal to), >, <,
>=, <= (greater than, less than, greater than or equal to, and less
than or equal to). For example number <= 100 checkes to see if the
value of the variable number is less
than or equal to ()100 and inputString
== "Tracy" checks to see if the value of the string() variable
inputString is verbatim "Tracy".
SAQ: Why does JavaScript (like, C, C++, and Java) use "= =" instead
of the more sensible "=" for "equals to"?
SAQ: What is the opposite of (a) the > operator and (b)
the >= operator?
- Boolean operators are
used in conditional expressions to compare Boolean (or string) operands, returning
a "true" or "false" result. For example, (Grade <= 100) AND
(Grade>=0) can be used to check that a grade entered is within the
proper range 0-100. A boolean operator incluse && (AND), ||
(or), and ! (unary NOT).
- Binary string operators are used to concatenate (+) or
compare (<, >, >=, and <+) strings, for example noun + "s"
would make the word in the string variable noun into a plural.
(An example of string comparison has already been given in section
C.b, above.)
- The assignment operators
(=, +=, and &=) assign the value of a quanty to their left to the variable
on their right. The simple assignment (=) is suplemented with (+=, -=, *=,
/= and &=) which are shorthand combining operations with assignments.
For example grade += curve () adds a curve
to a grade. The &= operator assigns the value of (lefthand
operand && righthand operand) to lefthand operand, e.g. valid
&= legitimate() adds an aditional
condition (the boolean variable legitimate) to the Boolean variable
valid.
SAQ: This use of "=" causes much of the strange arithmetic notation
in C, C++, Java, and JavaScript. Explain.
- SHIFT OPERATORS...
- Two rarely used operators, ? and typeof,
have no similar operators so they have no category.
- ? assigns a specified value to
a variable if a boolean quantity, condition, is true, otherwise
it assigns an alternate value if condition is false, e.g. grade
= (score >= 60)? "pass":"fail, assigns the value "pass"
or "fail" to grade depending on whether score
is equal to or greater than 60. (
I, personally avoid this operator because
it is not intuitive. Anything requiring this operator can be accomplished
using the more reader-friendly IF-THEN-ELSE. See section , below.)
- typeof returns the
data type of its operand, e.g. if (typeof name=="string") checks
to see if the value of name is of type string.
OPERATOR PREFERENCES...
- Statements in JavaScript:
- Statements are single instructions
that are executed, sequentially, by the JavaSript interpreter. A statement
consists of expressions made up of the variables and operators mentioned
above plus constants and literals. The various kinds of statement that
can appear in JavaScript inclue the following.
- Declarations of variables
(See section 2.B.d,
above.), definitions of functions (See section 3.B.b, below.), or
instantiation of objects create new quantities,
- Assignments assign evaluated
expressions on the left of the assignment statement, :=, to a
variable or object property on the right, e.g. x := x +1 adds one
to the current value of x and then assigns it as the new value of x.
- Control structures alter
the flow of execution, e.g. loop statements, selection statements (if
or switch constructs), break, continue, or return
statements (See section 4,
below.) can change the normal sequential execution of a block of statements.
- Function or method calls
(See section 3.B.e, below.) invoke
a built in function or method or a user-defined function; the function or
method is executed after which its results are applied in the statement containing
the call.
- Comments (See section 2.D.e, below.) allow text to be incerted
within JavaScript code which is ignored by the interpreter.
- Exception statements are
a sophisticated form of error handling.
These were adopted from Java
in JavaScript 1.4 and JScript 5.0.; however
since exceptions are not part of ECMA-262,
they are not covered further in this appendix.
- Conditional compile statements
allow JScript code to be compiled only under developer-defined
conditions. (
These are only available in JScript;
therefore, they are not covered further in this appendix)
- Statements are executed sequentially,
unless this is modified by a control structure; see section D.a.3, above.
- Unlike, most programming languages,
JavaScript does not require a semicolon to terminate a statement, unless there
are more than one statement on a single line. Although semicolons
are optional, it is a good habit to include them; this will help
you remember to do this in other languages.
In fact, since JavaScript syntax is virtually identical to C,
C++, and Java, when you code in JavaScript you are practicing write those
other languages.
- A block is a sequence
of statements that is enclosed in braces, "{" and "}", that is treated as
a whole by the JavaScript interpreter. Blocks of statements are typicallyt
used as the bodies of control structures or functions.
- Comments are statements
that are ignored by the interpreter executing the Javascript. They can
be inserted into JavaScript code two ways: Comments can also be used for
debugging -- you can "comment out" sections of code to prevent them from
being executed. By doing this, trial and error can help you identify the
statement that is causing a particular error.
- Single line comments must be preceded by two backslashes,
e.g.
//This is an example of a single line comment.
- Multiple-line comments blocks must be preceded with
/* and closed with */, e.g.
/* This is a
three line
comment */
Although comments are optional, they are a critical part
of programs in any language, because they explain the code to a user, or more
critically, to a future programmer who is trying to update or modify the
code. They are especially important when code examples are used
as teaching tools. In any case, remember that code is for the computer,
but comments are for humans.
- Top-Level properties and functions are those
that are not associated with specific objects in JavaScript, but are "built-into"
the core language and thus available to any developer using JavaScript
in any context (CSJS or SSJS). In ECMAScript they are described
as properties and functions of the "global object".
- There are three core properties of the global
object that not associated with any lower-level object.
- infinity is the core property that
specifies the corresponding undefined mathematical value.
- undefined is the core property that
specifies that a value has not be assigned to a variable. This value is assigned
to a variable, when it is declared, if the declaration statement assigns no
initial value.
- NaN is the core property that specifies
that the value of a variable or return value of a function is not a number.
-
There are nine core functions of the global
object that are built into core JavaScript but are not associated
with any lower-level object. (Note that there are also built-in methods
(functions associated with a specific object) that are provided by the various
object models that augment core JavaScript. However, the following
"functions" are not associated with any browser object.) Remember that
italics, fixed width text must be supplied by the developer, e.g. arg
represents an argument that must be created by the developer.
- escape(arg) returns the ISO Latin-1 character set equivalent of arg, e.g. escape("#") returns "%23".
- eval(arg) evaluates an expression
given in arg and returns the
result, e.g. eval(2+1) returns 3.
- isFinite(arg) returns a boolean
value that indicates whether or not arg is a finite number.
- isNAN(arg) returns true
if arg is NOT a number; otherwise
false is returned.
- Number(obj) converts the argument,
obj, (an object) to
a number and returns it.
- parseFloat(arg) returns the
floating point equivalent of a string number, e.g. parseFloat("2.5")
returns 2.5.
- parseInt(arg) returns returns
integer equivalent of a string number, e.g. parseInt("2") returns
2.
- String(obj) converts an object
to a string and returns the string, e.g. the sequence "dateObject = new
Date(1000000000000);
document.write(dateObject);" prints out "Sat
Sep 8 21:46:40 EDT 2001". - unescape(arg) returns , i.e. it reverses the result of escape, above, e.g. unescape("%23") returns "#".
Note the difference between built-in functions and user-defined
functions discussed in the next section. In general,
built-in functions and methods come with the particular JavaScript implementation
that the developer is using and can be used directly by the developer, but
developer-defined functions are new processing modules that must be created
by the developer and are typically coded within the head of an HTML document
and called from scripts within the body. (See the next section.)
3. CORE JAVASCRIPT, DEVELPER-DEFINED
FUNCTIONS:
- Developer-defined functions are the only
tool with which the JavaScript developer can create new code modules
with developer-specified processing capabilities. In object-oriented
languages, like Java, C++, Smalltalk, Ada95, Modula3, etc.(0),
this is accomplished by creating new classes which contain
both properties and methods. However, this facility is not available
in current JavaScript. (This is the reason it is called a "object
based ()" language, not an OOPL).
- Fortunately JavaScript uses the word "functions" to
identify this modules. This corresponds precicely to the terminology
of C++ where "functions" are stand-alone constructs that are not associated
with a specific class and "methods" are the equivalent that are defined
only within a class. (It should be remembered, here, that in pure object
oriented programming languages (OOPL), functions are not allowed, i.e. they
must be defined within a class where they are called "methods". This
is also true in JavaScript. It should also be noted that in Java
functions are not allowed; everything must be defined within a unique class.
This is what makes Java a "pure" OOPL.)
- JavaScript's built-in functions, called core
functions, have already been discussed, in section 2.E.b, above.
- Functions are implemented is JavaScript in
a maner similar to those in C and C++. However, unlike Java,
functions can exist, on their own, outside of a class. Fortunately
JavaScript does distinguish "functions" from "methods", i.e. methods
are, properly, "functions within an object".
- A functionis the construct for creating a named collection of instructions
that perform a specific operation or task. This allows the programmer to
"call" (or "invoke") a function by simply writing its name within JavaScript
code. Unless the function is "built-in", i.e.
provided by JavaScript itself, it must be defined, by the developer, before
it is used (invoked or called). Therefore, using functions can be subdivided
into defining functions and invoking (calling) functions.
- The function definition (often called declaration)
is a statement which specifies its name, arguments, and sequence of JavaScript
statements, i.e.
function functionName(argument1,argument2,etc){
//<concise description
of the function>
declaration
of local variables;
block
of statements;
}//end functionName
(
The comments, in bold, within the preceding,
syntax are my additions to the standard, minimal syntax of JavaScript.
Including a description of the function and clearly distinguishing the end
of the function are simply good programming habits that will help the user,
or a future developer, to understand your JavaScript code.)
- A function doesn't necessarily
require arguments. If a function has no arguments an empty set
of parentheses follows its name, i.e. functionName().
- If arguments are used,
they are used as variables, along with local variable, within the function
body (in statements which make up the function). The initial values of those
variables will be any values passed to the function in the function invocation
(call).
- Functions can be coded in
one of two locations:
- Function definitions are normally
placed within the header of an HTML document (between <head>
and </head>). Since an HTML document is interpreted line by line
starting at the top of the document, the function definitions are loaded
before they are callrd from scripts within the document body.
- Functions can be defined
in a separate file which are then accessed by using the source attribute,
src, of the <script> tag.
- There are two types of functions.
- A function may return a value,
via its name, to the calling expression, typically calculated using arguments
passed to the function, e.g. the function, factorial, returns the
factorial of number. (Note that, unlike the subsequent
type of function ("null function; see the next section), this kind of function
faithfully implements the mathematical concept of a function.)
function factorial(n){
//returns the iterative
factorial of number n
fac
= 1;
for (i=1; i<=n; i++)
{ fac = fac*i; }
return
fac;
}//end of iterative factorial
Recursive functions contain an invocation of themselves
within the function body; this is a form of repetition that is an
alternative to a iteration (looping) algroithm, like that of the preceeding
implementation of factorial(n). (See section 3.F.c, below on recursion as
a repetition control structures.) The recursive equivalent, where
the "recursive call" is highlighted in boldface, is:
function factorial(n) {
//returns the recursive
factorial of the number n
if ((n ==
0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}//end of recursive factorial
SAQ : Write a function that would return the power, p,
of a number, N, i.e. Np.
- A fuction may simply perform a task, without returning
a value, e.g. the following function, warning, prints a blinking
version of its argument, message. Such functions are often
called "null functions", a name that would make mathematicians shudder
(because, in math, a function, by definition returns a single
value). (
I think this use of the word "function"
is a misleading misuse of the mathematical concept of a function;
however, this conforms to the use of "function" in C, C++, and Java.
I think that a more appropriate term would be "procedure", the
word used in Pascal and the various languages based on Pascal (Modula 3,
Ada, Ada 95, etc. To distinguish functions that do not return a value
I will use the term "procedural function".))
function warning(message){
//prints a bold version
of message, passed as an argument
document.write("<b>message</b>");
}//end warging
- A function is invoded (called) by writing its name, with
specified values for its arguments, as a JavaScript statement or as part
of a JavaScript statement.
- A procedural function should
be a statement on its own, e.g.:
warning(" Remember this!");
- True functions (which return
a result) should be called from within an expression, e.g.
document.write("The factorial
of "+number+" is "+factorial(number);
- Since JavaScript is typically
associated with a GUI (graphical user interface) which are event driven,
JavaScript functions are often called from within event handlers;
this will be described in section 0.4, below.
4.
CORE JAVASCRIPT, CONTROL STRUCTURES:
Control strutures in JavaScript statements that
provide a way to modify the normal sequential execution of statements.
There are two types of structured control structures, selection () and repretition (). as well as an interruption
control structure and what might be called a shorthand construct,
with.
4.1
JavaScript has two kinds of selection constructs, if-else and switch
statement
- The syntax of the if-else construct, (See
Moncur, Hour 7.) the most general, structured selection construct
in any programming language, has a syntax identical to that in C, C++, and
Java. (Note that this is more clearly described as "if-then-else",
but, in ANSI standard C based syntax, the "then" is not explicitly coded,
as it is in Pascal based languages.) If a condition
(a boolean expression) evaluates to true then the block of true statements
is executed. The (optional) else clause specifies a block
of false statements which are executed if thecondition
evaluates to false. The else clause is optional in that it may be
omitted if there are no statements which need to be executed if the condition
is false. The syntax is:
if (boolean expression) {
block of true statements;
}
else {
block of false statements;
}//end if
Note that the //end if comment, though not required,
is good progamming paractice. An example of an if-else code (with single
statement for both cases) is:
if (Grade >= 60) {
document.write("Pass.");
}
else {
document.write("Oops!");
}//end if
- If-else statements may be nested, i.e. if-else
statements my be used in either the list of true statements block
or the list of false statements block, e.g.
if (Grade >= 90) {
document.write("Excellent.");
}else if (Grade >= 60){
document.write("Pass.");
}else {
document.write("Oops!");
}//end if
SAQ: Write a nested If-else statement that would print out the
grades "A", "B", "C", "D" or "F".
- The If statement, the simplest selection statement,
has no else clause; if the condition is true the block of true statementsis
executed otherwise nothing happens, e.g.
if (character = " ") {
document.write("Found a
space.");
numSpaces = numSpaces +1;
}//end if
SAQ: (a) Why isn't the else clause used in the preceding example?
(b) On its own this selection construct doesn't look very useful. How
could it be used in a larger script?
- The switchstatement
matches an expression with a particular case, and executes the statements
defined for that case. Note that, unlike the If-else, the conditional,
(expression), in is not a boolean () expression, i.e. it has a
particular value other that true or false. The switch statement
is not as flexible as the if-else statement, but in most cases, is
more readable than an equivalent nested if-else statements. In other
languages the switch statement normally called a "case statement,"
switch (expression){
case label :
block of statements;
break;
case label :
block of statements;
break;
...
default : statement;
}
For example, an alternative to the nested if-else
example, above, would be
switch (Grade){
case "A" :
document.write("Excellent!");
break;
case "average" :
document.write("Acceptable.");
break;
case "poor" :
document.write("Unacceptable.");
break;
default : document.write("You
don't fit into a typical category.");
}
SAQ : (a) In the preceding example, the case values
are strings, i.e. value of the variable Grade, whose type is string;
should case values always be enclosed in quotes? (b)Write a switch
statement that is equivalent to the if (Grade >=
60)example
above.
4.2
JavaScript has three kinds of repetition constructs, interation (looping)
and recursion.
- Reptetition has two distinct forms, iteration
(or looping) where a block of statements is repeated until an exit condition
is reached and recursion where a function continually calls itself
until a stop condition is reached.
- Iteration (looping; (See
Moncur, Hour 8.) has two basic
forms, definite loops which repeat statements a specified number of times
and indefinite loops which repeat until some external condition is met.
- Definite iteration,
in JavaScript, is used when the looping condition that is determined outside
the body of the loop, i.e. by a counter reaching its maximum value or a each
of a set of object properties has addressed.
- The for loop
is the most flexible construct for definite loops It repeates
a block of statements until a looping condition (a boolean, or true/false (), expression) is changed
to false. Normally, the number of times a loop
is repeated depends on a special variable called a counter. The syntax
of the JavaScript for statement:
for (initial-statement; looping-condition;
increment){
block of statements;
}//end for
The initial-statement is executed
only once; it is normally used to initialize the counter. Then the looping-condition
is tested, and if it is true, the block of statements is executed.After the
block is finished, the counter variable is incremented, the looping-condition
is tested again, and, if true, the block of loop statements is repeated.
This continues until the looping-condition turns to false; then the loop
is exited.For example, a loop that would print out all digits
for (i=0; i<10; i++) {
document.write(i);
}// end for i = 0 to 9
- The for...in
statementis specifically designed to cycle through each property of an
object. At each iteration of the loop, the index designates the
next property of the specific object, using the syntax:
for (index in object) {
block of statements;
}//end for...in
The following example from Moncur,
Hour 8, illustrates how a script can display each property of the Netscape
Navigator browser without having to know how many properties there are,
much what each property is.
for (i in navigator){
document.write("property:
" + i);
document.write("
value: " + navigator[i]);
}//end for...in
SAQ : What will the first line of the
execution of the preceding for..in look like?
- Indefinite iteration
has two forms in JavaScript. (Other languages have other forms, but
the while loop, which can handle any looping problem, is available
in all structured programming languages and object oriented programming languages.)
- The most general form
of indefinite iteration is the while statement executes
its statement block as long as the condition is true. This is called
indefinite" because, unlike definite repetition, the number of repetitions
is not specified before entering the loop; instead, thecondition
must change to false in one of the loop statements. The syntax is:
while (condition) {
block of statements;
}//end while
- Another indefinite
iteration, a do...while statement executes a block of
statements repeatedly until a condition becomes false. Due to its structure,
this loop necessarily executes the statement at least once.
do {
block of statements;
} while (condition)
SAQ : What is the difference between a while loop and a
do..while loop?
- Recursion is a completely
different form of repetition that is supported by most modern
programming languages. Recursion faithfully follows the mathematical
operation of the same name. Recursion is implemented in all programming
languages by a function calling itself. (See recursive functions, above.)
For example ((See the
Moncur Workshop, Displaying Scrolling Messages,
in Hour 7.)
function ScrollMessage()
{
window.status
= "Hello surfer....";
window.setTimeout("ScrollMessage()"
200);
}//end ScrollMessage
SAQ : What does the resursive function
ScrollMessage, above,
do?
SAQ: Recursion can be eiter definite or indefinite.
Which type is ScrollMessage? How could one change this to the other
form?
- The interruption constructs
in JavaScript are the break and continue
statements. Both of these statements may be used to jump out of a control
structure, continuing with the next statement following that control structure.
When used within the statement block of a loop, each statement behaves slightly
differently.
- break aborts execution of the control
structure; processing continues with the first statement following the control
structure.
- continue aborts the current execution
of a block of loop instructions and returns to the beginning of the loop
if the looping condition is still true; otherwise the loop is terminated
- The with
statement serves as a sort of shorthand, allowing a series of statements
to be executed with a specified object as the reference, i.e., the object
specified in the with statement is used as the default object
whenever a property occurs without a specified object The syntax is:
with (object) {
block of statements;
}//end with
5. JAVASCRIPT'S
CORE OBJECT MODEL (COM, Tony's acronym.), A LIBRARY OF BUILT-IN "CLASSES":
WARNING: Unfortunately JavaScript, being an object
based language, uses the word "object" for quantities that in object-oriented
languages are called "classes ()", so be careful, especially when trying generalize JavaScript
concepts to other programming languages or trying to relate JavaScript to
your experience with other programming languages. To minimize confusion I use "abstract object"
when referring to the JavaScript equivalent of OOPL classes and "real object" (or "instance") when referring to the javaScript
equivalent of the OOPL instances (called "objects" in C++ and Java).(If you are still unclear about this, reread section 1.B.a, above and
review the study
guide, section 3.2.1.1.)
- Object oriented programming
languages (OOPL) are founded on the concept of a class, an abstract
"template" that completely specifies a programmable quantity. In fact,
in pure OOPL like Java, all code is encapsulated within classes,
i.e.
object oriented programming really means
(1) creating classes and (2) relating them in what is called a software architecture. The built-in functionality in OOPL come in the form of
class libraries which can be used by the developer; each class
of the library provides attributes() (that specify the state of the class) and methods () (that
specify the behavior of the class). (
Unfortunately, as I have warned numerous
times, JavaScript does not use the word "class"; instead, it uses the word "object". Therefore, to
relate JavaScript to other OOPL think of "class" when you see the word "object"
in JavaScript. I will add the word "abstract" before "object" when
this should be related to an OOPL "class".)
- For example, in Java a
graphical object called Point2D, modelling a two dimensional point,
would have properties x and y (with "fully qualified names"
Point2D.x and Point2D.y.) and methods move(dx,
dy), center(x,y), etc. (In OOPL like Java, C++, etc.
Point2D would be a class (), x and y would be attributes ();
the methods (thank goodness) are methods everywhere!)
- The "object" is the encapsulation construct
of JavaScript. It is a collection of elements (properties () and
associated methods ()) all encapsulated under a single name, i.e. they are accessed
by the standard "dot notation", objectName.elementName.
which can consist
of a sequence of object names, separated by periods that define the hierarchy
of the object. For example,
window.document.image["image1"]
identifies an image named "image1" that is part of the document
displayed in the current window of a browser. Note that both the object name and element name are case sensitive.
- An object's properties completely
define the object's state.
- The word "property", like
"object", is used in two contexts JavaScript.
- The "property" of an abstract
object is analagous to an attribute of an OOPL class, i.e. properties
are "empty templates" for the variables of a real object. These abstract
properties are the things that you write when you actually code JavaScript
scripts and functions.
- The "property" of a real
object is analagous to a variable of an OOPL instance, i.e. properties
of real objects must have values that define the state of the real object.
These real properties are created, by the JavaScript interpreter, when it
executes the code embedded within an HTML document.
Note that this dual use is also
common in OOPL, i.e. the word "attribute" is used to describe the state
of classes as well as the state of instances of those classes. I prefer to use the word "variable" for instances, reserving
"attribute" for classes, i.e. variables
are real quantities and attributes are abstract quantities.
This conforms to terminology of structured programming, i.e. variables (real
quantities) are created by declaring them to be be of a specified "type"
(an abstract quantitiy). Computer science
students might like to pursue this concept by reading the discussion,
in the context of Java, in LM I of COSC 390. - Properties are accessed with the JavaScript identifier,
objectName.propertyName(). A property of an abstract object actually becomes,
when that object is instantiated, a variable of the real object, e.g.
window.document.image["image1"].src
identifies the src property (attribute) of the window.document.image object, discussed above. Its value
would be the URL that specifies the location of the image. -
You assign values to the properties
(variables) of a real object with the standard syntax:
objectName.propertyName()=
value;
e.g. document.bgColor = "white";
assigns the color white to the background of the HTML document
being displayed in a browser window. - You can create a new property by simply initializing
it (assigning it a value), e.g.
Name.first = "Tony";
which assigns the value "Tony"() to the property first() of the object Name(). See section 5.G, below, for the
details of this process. - JavaScript objects are implemented as arrays. Therefore,
an object's properties can be accessed either by using the dot notation illustrated
above, or by using an array syntax, e.g.
Name["first"] = "Tony";
Name["last"]() = "Tracy";
document.write(Name["first"]);
- An object's methods completely
define its behavior in the form of operations that can be performed on the
object. These are syntactically identical to functions except for their
naming syntax, which specifically associates a method with the object for
which it is defined, i.e.
objectName.methodName()
- objectName may
be a sequence of object names that are hierarchically related in an object
model. See section 5.B, above,
and the schematic of the W3C DOM, below.
- The arguments that pass
values to the method are specified, within the parentheses, as a comma delimited
sequence, just like a normal function call. For example, in the statement
window.document.write("comment1");
the value (text) of the variable comment1()is
passed to the write() method of the document() object contained within the window()object.
When executed by the browser, this statement causes the text in comment1
to be displayed in the current HTML page. - It is important to note that the definition
and syntax of JavaScript methods conform to standard OOP terminology.
SAQ: What is the difference between a function and a method?
- { CONSTRUCTOR
AN OBJECT OBJECT}
- { OOP
FEATURES, FORWARD REFERENCE?}
- When writing scripts or functions
in JavaScripts, the developer can use built-in objects (associated
with, but part of, the language itself; see the COM and DOM, below.)
or create user-defined objects from other objects. The numerous built-in
objects allow the developer to access and utilize Web page elements
as well as the Web browser.
- In fact, proficiency with
the built-in objects is essential to the mastery of the JavaScript, more
so than most other programming languages.
- In general, an object
model (OM) is a hierarchical collection of objects, complete with attributes/properties
and methods, that is available for use by software developers. Thus it is
an independent resource that can be combined with core language constructs
to agument that language. In Web development there are two basic type
of OM:
- The Core Object Model
(COM, Tony's term), described in this section, is the platform independent
OM specified by the W3C.
- Various document object models
(DOMs) specified by the W3C as well as the various browsers (e.g. Netscape
Navigator and Internet Explorer)
- W3C DOM
- Netscape 4 DOM
- Internet Explorer 4
- Internet Explorer 5
- Core Objects
(Note that the constructor is essentially the same in all of the following
abstract objects, i.e. it has the name of the object followed by "()"
,and it invokes the constructor of the particular object.)
- Array object
(See Moncur, Appendix D.)
-
- Boolean object
- Date object (See Moncur, Appendix D.)
- Properties:
- constructor, Date()
- prototype which returns the prototype
of the object, used to extend the object's interface.
- Methods (42 of 44 are defined
in ECMA-262 and are, therefore, platform independent):
- sixteen "set" methods allow the developer to
specify a time or date, i.e.
- setTime(), setDate(), setMilliseconds(),
setSeconds(), setMinutes(), setHours(), setMonth(), setYear(),
and setFullYear() specify the local times or dates.
- setUTCDate(), setUTCMilliseconds(), setUTCSeconds(),
setUTCMinutes(), setUTCHours(), setUTCMonth(), andsetUTCFullYear()
specify the times or dates adjusted to universal (GMT) time.
- nineteen "get" methods allow the developer
to retrieve the time or date. They include the "get" equivalent of
the preceding "set" methods plus getDay(), getUTCDay(), and getTimezoneOffset() the last of which returns
the difference, in minutes, between the local time and the UTC.
- seven "converter" methods that change between
the various formats of time, date, and time zone (compared to the UTC (GMT)
standard.
- parse() returns the number of milliseconds
in the local time and date since midnight, 1/1/1970.
- UTC() returns the UTC equivalent of parse().
- toGMTString() converts the text (string)
equivalent of the Date object based on UTC.
- toLocaleString() converts the Date
object's time to text (string) based on local time.
- toSource() returns a string containing the
source code for the Date object.
- toString() returns the text (string) equivalent
of the Date object.
- ValueOf() returns the primative value of
the Date object.
Two methods, getVarDate()
and toUTCString, are not included
above because they are not part of ECMA-262. - Event object (
not mentioned in Moncur) represents a javaScript event. Event objects
are created, automatically, when a browser event occurs; they can NOT
be created by the user. A reference to a specific event retrieved by
passing event, as a parameter, to the event handler.
- Properties (Note that there is
no constructor() because the Event object can not be instantiated.)
- ScreenX
- ScreenY
- type
- x
- y
- Methods: none
- Function
object
- Math object (See Moncur, Appendix D.)
- Properties (Note that there is
no constructor() because the Math object can not be instantiated.) are all
universal math constants, i.e.:
- five provide constants associated with logarithms,
E, LN2, LN10, LOG2E, and LOG10E.
- one, circle constant, PI, and
- the square root of 2 (approximately .707) and the
square root of 1/2 (approximately 1.414).
- Methods (all 18 are platform
independent and are defined in ECMA-262):
- six trigonometry methods, sin(x), cos(x), tan(x), asin(x), acos(x),
atan(x) (x)and
atan2(x)) that return the trigonometric values of their
argument, x.
- two logarithmic methods , exp(), and
log(), tha