Full HTML for

Basic foilset Overview of JavaScript I -- Basic Web Scripting Language

Given by Geoffrey C. Fox (Tom Scavo) at CPS616 Technologies of the Information Age on Spring Semester 99. Foils prepared 3 March 99
Outside Index Summary of Material


Java vs. JavaScript, Interpreters vs. Compilers
JavaScript Basics and Syntax
JavaScript Core Objects
JavaScript Events
Client-side JavaScript (the basic browser AWT)
JavaScript Object Model
Following Lecture Set is Advanced Topics:
  • Cookies, LiveConnect, and LiveWire, Security, W3C DOM, Dynamic HTML
Some of this material was prepared by Tom Scavo

Table of Contents for full HTML of Overview of JavaScript I -- Basic Web Scripting Language

Denote Foils where Image Critical
Denote Foils where Image has important information
Denote Foils where HTML is sufficient
denotes presence of Additional linked information which is greyed out if missing

1 CPS616 Web Technologies Lectures on JavaScript I Basic Web Scripting Language and use in HTML Pages
2 Outline
3 JavaScript Resources for Foil 3 General Remarks
4 NPAC JavaScript Examples Why would you use JavaScript I?
5 Why would you use JavaScript II?
6 NPAC DHTML Examples Why would you use JavaScript III?
7 Why would you use JavaScript IV?
8 Microsoft Jscript Manual Version History
9 Whats New in JavaScript 1.2 JavaScript 1.2
10 Microsoft Jscript Manual JScript 3.1
11 JavaScript Standards for Foil 11 ECMAScript
12 Java vs. JavaScript I
13 Java vs. JavaScript II
14 Java vs. JavaScript III
15 Java vs. JavaScript IV
16 Performance Issues
17 JavaScript Basics
18 We Need to Know HTML!
19 JavaScript Scripts for Foil 19 JavaScript Scripts
20 "Hello World" Example
21 Simple scripts for Foil 21 "Hello World" Example (cont'd)
22 Form Example
23 Form Example Form Example (cont'd)
24 Some Parameterized HTML Links for Foil 24 Example of Parameterized HTML
25 The <SCRIPT> Tag
26 The SCRIPT Tag for Foil 26 The <SCRIPT> Tag (cont'd)
27 The SRC Attribute The <SCRIPT> Tag (cont'd)
28 JavaScript URLs for Foil 28 JavaScript URLs
29 JavaScript Entity JavaScript Entities
30 JavaScript Syntax
31 JavaScript Syntax for Foil 31 Basic Syntax
32 JavaScript Variables for Foil 32 Variables
33 Operators for Foil 33 Operators
34 Expressions for Foil 34 Expressions
35 Reserved Words
36 Statements for Foil 36 Statements
37 IF-THEN-ELSE for Foil 37 The if Statement
38 The switch Statement The switch Statement
39 Iteration and Recursion for Foil 39 The for Statement
40 General Iteration for Foil 40 The while Statement
41 More Iteration for Foil 41 The do...while Statement
42 The with Statement
43 JavaScript Core Objects
44 JavaScript Object Model for Foil 44 Basic Concepts
45 Built-in Functions for Foil 45 The Global Object
46 The eval() Function The eval Function
47 Parsing Functions for Foil 47 Parsing Functions
48 Other Global Functions
49 Authoring Guide, Predefined Core Objects and Functions Built-in Objects
50 Array Objects for Foil 50 Array Objects
51 Array Methods Array Methods
52 Boolean Objects for Foil 52 Boolean Objects
53 The Date Object for Foil 53 Date Objects
54 Date Methods for Foil 54 Date Methods
55 Function Objects for Foil 55 Function Objects
56 Function Arguments
57 The Math Object
58 Math Properties Math Properties
59 Math Methods for Foil 59 Math Methods
60 Number Objects
61 Number Properties
62 Number Properties (cont'd)
63 Object Objects
64 RegExp Objects I
65 RegExp Object RegExp Objects II -- Examples
66 Regular Expressions for Foil 66 RegExp Objects III -- String Methods
67 Simple Regular Expression Patterns
68 Regular Expressions -- Special Characters
69 Grouping Patterns in Regular Expressions
70 Anchoring and Alternation in Regular Expressions
71 Parentheses in Regular Expressions
72 The Backslash \ Operator
73 Static Properties of RegExp Object I
74 Static Properties of RegExp Object II
75 Some Regular Expression Examples
76 Examples of Replace and test
77 Examples of match (string) and exec (RegExp)
78 Multiple Calls to exec Method
79 String Objects
80 String Methods for Foil 80 String Methods
81 String Methods (cont'd)
82 JavaScript Events
83 Authoring Guide, Handling Events Events
84 Event Handlers for Foil 84 Event Handlers
85 Event Handlers for Foil 85 Event Handlers (cont'd)
86 New Event Handlers for Foil 86 Event Handlers (cont'd)
87 Event Handler Examples
88 The Event Object Event Object
89 The Event Object for Foil 89 Event Object (cont'd)
90 Client-side JavaScript
91 Authoring Guide, Using Navigator Objects Object Hierarchy
92 Object Referencing Object Referencing
93 Authoring Guide, Using Windows and Frames Window and Frame Objects
94 Window Properties for Foil 94 Window Properties
95 Window Properties (cont'd)
96 Frame Properties for Foil 96 Frame Properties
97 Frame Example
98 Frame Example (cont'd)
99 Frame Example (cont'd)
100 Frameset Documents for Foil 100 Frameset Documents
101 Window and Frame Methods for Foil 101 Window and Frame Methods
102 History Properties and Methods for Foil 102 History Object
103 The Location Object for Foil 103 Location Object
104 Document Properties for Foil 104 Document Object
105 Document Properties
106 Document Properties Document Properties (cont'd)
107 Document Methods for Foil 107 Document Methods
108 Form Objects for Foil 108 Form Objects
109 The form Property Form Properties
110 Form Methods
111 Image Objects Image Objects
112 Animation for Foil 112 Image Animation
113 Layers for Foil 113 Layer Objects
114 Built-in Arrays
115 HTML-reflected Arrays
116 Client-side String Methods for Foil 116 Client-side String Methods
117 Navigator Object for Foil 117 Navigator Objects
118 Displaying All MimeType Objects MimeType Objects
119 Plugins for Foil 119 Plugin Objects
120 JavaScript Object Model
121 How to define Objects in JavaScript
122 User-defined Objects
123 User-defined Methods
124 Another Example
125 The prototype Property
126 The prototype Property (cont'd)
127 Prototype-based Inheritance

Outside Index Summary of Material



HTML version of Basic Foils prepared 3 March 99

Foil 1 CPS616 Web Technologies Lectures on JavaScript I Basic Web Scripting Language and use in HTML Pages

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Geoffrey Fox
Northeast Parallel Architectures Center
Syracuse University
111 College Place
Syracuse, NY 13244-4100
http://www.npac.syr.edu/projects/tutorials/JavaScript/
http://www.npac.syr.edu/users/gcf/javascriptImarch99/

HTML version of Basic Foils prepared 3 March 99

Foil 2 Outline

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Java vs. JavaScript, Interpreters vs. Compilers
JavaScript Basics and Syntax
JavaScript Core Objects
JavaScript Events
Client-side JavaScript (the basic browser AWT)
JavaScript Object Model
Following Lecture Set is Advanced Topics:
  • Cookies, LiveConnect, and LiveWire, Security, W3C DOM, Dynamic HTML
Some of this material was prepared by Tom Scavo

HTML version of Basic Foils prepared 3 March 99

Foil 3 General Remarks

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Resources for Foil 3
JavaScript (originally called LiveScript) is a web scripting language for clients and servers
Client-side JavaScript facilitates rapid prototyping and is more responsive than CGI
Client-side JavaScript is particularly useful for frameset documents and HTML forms
Refs: JavaScript, The Definitive Guide by David Flanagan (3rd ed, O'Reilly, 1998); The JavaScript Bible by Danny Goodman (3rd ed, IDG, 1998); Dynamic HTML, The Definitive Reference by Danny Goodman (1st ed, O'Reilly, 1998).
Download the latest JavaScript manuals from Netscape http://developer.netscape.com/tech/javascript/index.html

HTML version of Basic Foils prepared 3 March 99

Foil 4 Why would you use JavaScript I?

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index NPAC JavaScript Examples
Originally JavaScript was designed to do what you think Java should do -- elegant dynamic animation on the client side
Then along came Java and JavaScript was eclipsed as it was just Netscape and not so well designed
Netscape tried to make it a server side language (LiveWire) instead of Perl but Java was much better here as well
JavaScript lived on for simple arithmetic on client side to produce somewhat better frames (as clicking on a link can call a JavaScript function instead of just loading a URL) and to quickly check forms client side without going back to server which is slow
A serious weakness was that dynamic aspects of JavaScript could only be used at "load" time and other changes of JavaScript required a "reload" which is real ugly and slow

HTML version of Basic Foils prepared 3 March 99

Foil 5 Why would you use JavaScript II?

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Then along came Microsoft and Netscape became distracted and quality of Java on the client side suffered and in fact is still problematical as Java in the browser has poor performance and lags Sun's version
Further the Web Consortium W3C never really liked Java butting in and thought HTML was the answer
JavaScript is Java with HTML and browser as AWT
W3C came along with XML and the DOM (Document Object Model)
In particular dynamic HTML extensions allowed one to get many benefits of JavaScript dynamically without reloading ....
Now all this was screwed up in version 4 browsers -- especially by Netscape -- and so the vision was obscured!

HTML version of Basic Foils prepared 3 March 99

Foil 6 Why would you use JavaScript III?

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index NPAC DHTML Examples
So Java is a good low level tool and how you program your stock market simulation downloaded from the online broker
However dynamical HTML and JavaScript is becoming preferred method of client implementations
Use JavaScript to manipulate "components of documents" and Java to do arithmetic
  • e.g. suppose you want to make your site accessible to blind. Then JavaScript identifies document components and hands text nuggets to Java voice synthesizer and image to fancy captioning system
As world develops HTML + JavaScript will become XML and HTML -- both with JavaScript to capture dynamic issues
On Server, Java always wins (unless you use C++ for performance)

HTML version of Basic Foils prepared 3 March 99

Foil 7 Why would you use JavaScript IV?

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Typically JavaScript is invoked from HTML and HTML text and JavaScript text are intertwined
If you need to make a dynamic page from C++ Perl or Java you must write the HTML from these languages
You can invoke applets from HTML but HTML and applet actions are not linked. In case of JavaScript HTML and JavaScript are closely linked
JavaScript is an example of an important concept -- the domain specific interpreter which we can expect to be of growing importance
  • Note Postscript is an interpreter for text layout; MATLAB an interpreter for Matrix arithmetic, Mathematica or Maple for Mathematics .....
Text ...................................................... Computer Language HTML---> JavaScript Java <----- C++

HTML version of Basic Foils prepared 3 March 99

Foil 8 Version History

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Microsoft Jscript Manual
JavaScript 1.0 debuted in NN 2.0 (Feb 96)
JavaScript 1.1 appeared in NN 3.0
NN 4.0 (a.k.a. Communicator) supports JavaScript 1.2
MSIE 3.0 introduced JScript 2.0, a subset of JavaScript 1.1
JScript 3.x is supported in MSIE 4.0
JScript 3.0 and later from IE are ECMA-compliant [Standard ECMA-262, June 1997] as is JavaScript 1.1 and following versions from Netscape
JavaScript 1.3 and 1.4 released with modest changes including better exception handling and Java-JavaScript linkage

HTML version of Basic Foils prepared 3 March 99

Foil 9 JavaScript 1.2

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Whats New in JavaScript 1.2
New features in JavaScript 1.2 (NN4.0):
  • Event object and event capturing
  • Ten new event handlers
  • Nested functions; new Number() and String() functions
  • New statements: switch and do...while
  • Many new methods and properties (especially for Window, String, and Array objects)
  • Perl4-compatible regular expressions
  • Signed script security model

HTML version of Basic Foils prepared 3 March 99

Foil 10 JScript 3.1

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Microsoft Jscript Manual
New features in JScript 3.1 (MSIE4.0):
  • Conditional execution (meta-statements)
  • New event handlers (39 in all!)
  • New statements: switch and do...while
  • Two new identity operators (=== and !==) which insist on variable types matching (default is to convert types in == and !=)
  • Perl4-compatible regular expressions
  • Debugger support
Adequate documentation is lacking, however

HTML version of Basic Foils prepared 3 March 99

Foil 11 ECMAScript

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Standards for Foil 11
ECMAScript refers to standard ECMA-262 released in June 1997
ECMAScript is essentially JavaScript with all client and server-side features removed i.e. It is the language and not the browser AWT handler
The emerging HTML and XML Document Object Models (DOMs) will be bound initially to ECMAScript
So one can use ECMAScript in several different domains (HTML XML VRML ...) by adding support for appropriate domain specific objects
Netscape Site has ECMAScript standard document

HTML version of Basic Foils prepared 3 March 99

Foil 12 Java vs. JavaScript I

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Sun's Java is fast becoming a broad industry standard
Java is well designed and documented
Java is object-oriented with (single) inheritance
Java is class-based
JavaScript is primarily supported by Netscape and Microsoft
JavaScript started quite "roughly" but is improving in design -- however some issues connected to browser are totally ill defined as browser ill defined -- e.g. what happens in what order when frames loaded ....
JavaScript is object-based with no class structure
JavaScript is prototype-based

HTML version of Basic Foils prepared 3 March 99

Foil 13 Java vs. JavaScript II

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Java classes and instances are distinct
A Java class has zero or more constructors
Java property inheritance follows class hierarchy
In Java, no way to add properties at run-time
JS object definition and constructor are identical and defined like methods
JavaScript property inheritance follows prototype chain
JavaScript properties may be added or removed at run-time
So essentially in JS, class structure is totally dynamic (a.k.a. Ill defined)

HTML version of Basic Foils prepared 3 March 99

Foil 14 Java vs. JavaScript III

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Java applets are distinct from HTML
Java is strongly typed with static (compile-time) binding
Java bytecodes are interpreted (or "Just-In-Time" compiled) on the client
JavaScript is tightly coupled with HTML
JavaScript is loosely typed with dynamic (run-time) binding
High-level JavaScript source code is interpreted on the client but is often MUCH faster than Java as integrated into browser

HTML version of Basic Foils prepared 3 March 99

Foil 15 Java vs. JavaScript IV

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Typical Java applet Structure
  • Java source --> javac compiler --> JavaVM Universal Machine code in .class file
  • Store JavaVM .class files on Web Server
  • Download JavaVM from Server to Client
  • Interpreter built into browser, reads JavaVM and executes on client
  • (User or System) Java event handlers interpret events within applet
Typical JavaScript Structure
  • JavaScript Source is included in HTML text or special .js files included in HTML files
  • Combined JavaScript and HTML is downloaded and interpreted by browser on client to produce HTML Page
  • Events (not in applets but) in HTML Page (mouse clicks etc.) are either interpreted by browser default or overridden by user JavaScript code.

HTML version of Basic Foils prepared 3 March 99

Foil 16 Performance Issues

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Typically, up to 106 C instructions may be executed in a few milliseconds (the time it takes a person to notice anything!) as one instruction in 1 clock cycle (say 108/sec)
A Java interpreter is roughly 50 times slower than C
Java "Just-In-Time" compiler is roughly 2–8 times slower than C whereas a native Java Compiler (and perhaps future JIT's) are about same speed as C
Perl is 500 times slower than C (an interpreter but analyses whole code before interpreting)
  • Runtime (e.g. I/O) can be as fast as C as it is C!
Tcl, JavaScript (true interpreters) are 5000 times slower than C
  • BUT If Java Script in browser invokes optimized C++ internal function, it can easily outperform Java
  • Just as Java itself can of course invoke through JNI C++ code.
  • Need C++ library to be built in as do not want to download

HTML version of Basic Foils prepared 3 March 99

Foil 17 JavaScript Basics

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 18 We Need to Know HTML!

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Like most interpreters (just look at BASIC), JavaScript has a huge and growing number of methods and properties corresponding to the many different features in a browser window
To study JavaScript, we will need to use all the features of HTML including
  • Frames
  • Forms -- including event handlers
  • Cookies
  • Layers and Dynamic HTML

HTML version of Basic Foils prepared 3 March 99

Foil 19 JavaScript Scripts

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Scripts for Foil 19
A script is enclosed in a <SCRIPT> container: <SCRIPT LANGUAGE="JavaScript"> ... </SCRIPT>
Scripts may be put in the <BODY> or the <HEAD>, depending on your needs
Use <NOSCRIPT>...</NOSCRIPT> for JavaScript-disabled browsers

HTML version of Basic Foils prepared 3 March 99

Foil 20 "Hello World" Example

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
<HTML>
<HEAD><TITLE>An Example</TITLE></HEAD>
<BODY>
<!-- Insert HTML here -->
<SCRIPT LANGUAGE="JavaScript">
document.writeln("<H1>Hello World!</H1>");
</SCRIPT>
<!-- Insert more HTML here -->
</BODY>
</HTML>

HTML version of Basic Foils prepared 3 March 99

Foil 21 "Hello World" Example (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Simple scripts for Foil 21
There is only one JavaScript statement: document.writeln("<H1>Hello World!</H1>");
The writeln method writes its argument into the current document
The script is in the <BODY> since it writes HTML code into the document; other scripts are written in the <HEAD> so they are processed and available in body
  • Actually in advanced applications, when JavaScript is actually defined becomes quite tricky and is an example of how there are intrinsically undefined features in language
Scripts may be hidden from old browsers using arcane construct <SCRIPT LANGUAGE="JavaScript" > <!-- A comment to a dinosaur .... Bunch of Exciting JavaScript Statements ..... //script ends here --> </SCRIPT>

HTML version of Basic Foils prepared 3 March 99

Foil 22 Form Example

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
<HTML>
<HEAD><TITLE>JavaScript with Forms</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function compute() {
if ( window.confirm("Is this what you want?") )
aForm.result.value = eval(aForm.expr.value);
}
</SCRIPT></HEAD>
<BODY><FORM NAME="aForm"> Enter expression:
<INPUT TYPE="text" NAME="expr" SIZE=15>
<INPUT TYPE="button" VALUE="Compute!"
onClick="compute()"> <BR> Result:
<INPUT TYPE="text" NAME="result" SIZE=15>
</FORM></BODY>
</HTML>

HTML version of Basic Foils prepared 3 March 99

Foil 23 Form Example (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Form Example
confirm is a method of the Window object which pops up a window requesting confirmation of requested action
eval is a built-in JavaScript function
onClick is a JavaScript event handler and onClick ="your stuff" executes JavaScript code yourstuff
Note the user-defined names (aForm, expr, result) referred to in the script

HTML version of Basic Foils prepared 3 March 99

Foil 24 Example of Parameterized HTML

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Some Parameterized HTML Links for Foil 24
<HTML><HEAD><TITLE>JavaScript Used to Parameterize HTML</HTML>
<SCRIPT LANGUAGE="JavaScript" > var imagewidth=600;// These could be changed by form var imagefile="npac.gif"; //input or some computation // based on size of window (available to JavaScript) </SCRIPT></HEAD>
<BODY> <h2>Plain old HTML of any type</h2> ...... <SCRIPT LANGUAGE="JavaScript" > document.writeln(`<imag align=top width=` + imagewidth + `src="' + imagefile +'" >'); </SCRIPT>
<b>And the beat goes on ...</b>
</BODY></HTML>
Note the horrible mix of ` (JavaScript) and " (HTML)
JavaScript Variables

HTML version of Basic Foils prepared 3 March 99

Foil 25 The <SCRIPT> Tag

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
If you have two versions of a JavaScript script, you can load one or the other:
<SCRIPT LANGUAGE="JavaScript1.1">
// Ignored by Navigator 2.0:
location.replace("newVersion.html");
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
// Read by Navigator 2.0 and above
</SCRIPT>
The newest version is "JavaScript1.2"

HTML version of Basic Foils prepared 3 March 99

Foil 26 The <SCRIPT> Tag (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The SCRIPT Tag for Foil 26
Multiple <SCRIPT> tags are allowed
Within a single <SCRIPT>, a function may be called before it is defined
Within a single document, a function defined in one <SCRIPT> may not be called from a previous <SCRIPT>
In particular, a function defined in the <BODY> may not be called from the <HEAD>

HTML version of Basic Foils prepared 3 March 99

Foil 27 The <SCRIPT> Tag (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The SRC Attribute
JavaScript code may be stored in an external file (and is therefore reusable):
<SCRIPT SRC="JScode.js"> // The body of this <SCRIPT> is // executed only if "JScode.js" // is not found! document.write("File not found!"); </SCRIPT>
An external file must have a .js extension and the server must be configured properly

HTML version of Basic Foils prepared 3 March 99

Foil 28 JavaScript URLs

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript URLs for Foil 28
A trivial example of a JavaScript URL is javascript:alert("Hello World!")
A JavaScript URL may appear anywhere an ordinary URL is expected: <A HREF="javascript:history.back()">Previous Page</A>
Note must use <A HREF=" javascript: void(anyoldfunction())" > if you do not want link to be invoked!
  • Use HREF="javascript: void(0)" if no action at all -- used if real action from onclick or other event handle for link
Navigator even has a mini-scripting environment invoked by typing javascript:into the browser's location text field
  • This is now (NN4.5) used to display error messages as a console instead of alternative (and clumsy) stream of windows (one per error ....)

HTML version of Basic Foils prepared 3 March 99

Foil 29 JavaScript Entities

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Entity
One can parameterize HTML using document.write(ln) commands such as:
document.writeln("string1" + Jsvariable + "string2");// etc.
There is another way of achieving this without a <SCRIPT> tag and no document.writeln -- namely
<IMG width="&{JSvar1};" src="&{JSvar2}" >
where JSvar1 and JSvar2 are JavaScript variables holding width and URL of image
Syntax is modeled on that for special characters where
  • > is > etc.
Such JavaScript Entities can only appear on right hand side of attributes values and cannot appear in HTML text such as titles
  • document.writeln approach has no such restriction!

HTML version of Basic Foils prepared 3 March 99

Foil 30 JavaScript Syntax

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 31 Basic Syntax

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Syntax for Foil 31
JavaScript syntax resembles Java and C
Braces { } are used for grouping
Use single or double quotes (equivalently) around string literals
Escapes: \b \t \n \f \r \" \' \\
Other literals: null, true, and false
JavaScript is case-sensitive while HTML is not (which sometimes leads to problems!)

HTML version of Basic Foils prepared 3 March 99

Foil 32 Variables

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Variables for Foil 32
Variables (identifiers) must begin with a letter, underscore, or dollar sign:
  • var := [a-zA-Z_$][a-zA-Z0-9_$]*
Declare variables in var statements: var aNumber = 137; var aString = "1";
JavaScript "entities" in HTML attributes: <IMG SRC="&{v1};" WIDTH="&{v2};"> where v1 and v2 are JavaScript variables

HTML version of Basic Foils prepared 3 March 99

Foil 33 Operators

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Operators for Foil 33
Assignment operators: = += -= *= /= %= <<= >>= >>>= &= ^= |=
JavaScript supports the usual arithmetic operators, as well as: % ++ --
Concatenation operator: +
Bit operators: & | ^ ~ << >> >>>
Relational operators: == > >= < <= !=
Logical operators: && || !

HTML version of Basic Foils prepared 3 March 99

Foil 34 Expressions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Expressions for Foil 34
Examples:
  • sum += x; // sum = sum + x
  • r -= n; q++;
  • s = "temp" + 1; // assign "temp1" to s
  • phi = (1 + Math.sqrt(5))/2;
  • valid = (age > 21 && age <= 65);
An if-expression returns a value:
  • p = ( k < 0 ) ? 1/y : y;

HTML version of Basic Foils prepared 3 March 99

Foil 35 Reserved Words

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 36 Statements

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Statements for Foil 36
JavaScript statements include: break, continue, do, for, function, if, return, switch, var, while, and with
Multiple statements on one line are separated by semicolons
Statement blocks are delimited by braces
Comments come in two flavors: /* any text including newlines */ // comment terminated by newline

HTML version of Basic Foils prepared 3 March 99

Foil 37 The if Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index IF-THEN-ELSE for Foil 37
Assuming boolean variable isWhite:
if ( isWhite ) {
document.bgColor = "pink";
isWhite = false;
} else {
document.bgColor = "white";
isWhite = true;
}
The else block is optional, of course

HTML version of Basic Foils prepared 3 March 99

Foil 38 The switch Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The switch Statement
The switch statement is new is JS 1.2: switch ( fruit ) { case "oranges": price = 0.59; break; case "apples": price = 0.32; break; case "bananas": price = 0.48; break; default: price = null; }

HTML version of Basic Foils prepared 3 March 99

Foil 39 The for Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Iteration and Recursion for Foil 39
A simple for-loop:
// Compute x^k for k > 0:
for (var y=1, i=0; i<k; i++) {
y *= x;
}
Here is another type of for-loop:
for (var prop in object) {
statements
}

HTML version of Basic Foils prepared 3 March 99

Foil 40 The while Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index General Iteration for Foil 40
A more general looping structure:
// Compute r = m % n for m,n > 0:
var r = m;
while ( r >= n ) {
r -= n;
}
break, labeled break, and continue are permitted in for and while loops
JavaScript supports recursion as well

HTML version of Basic Foils prepared 3 March 99

Foil 41 The do...while Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index More Iteration for Foil 41
A do...while loop tests its condition at the bottom of the loop: do { statements } while ( condition );
In this case, the statements in the loop body are guaranteed to execute at least once
This loop is new in JavaScript 1.2 and JScript 3.0

HTML version of Basic Foils prepared 3 March 99

Foil 42 The with Statement

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
with ( someObject ) { statements }
someObject is the default object used for any unqualified object references: with ( Math ) { area = PI*r*r; // Math property PI x = r*cos(theta); // Math method cos y = r*sin(theta); // Math method sin }

HTML version of Basic Foils prepared 3 March 99

Foil 43 JavaScript Core Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 44 Basic Concepts

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index JavaScript Object Model for Foil 44
JavaScript is object-based with no classes and, hence, no (class) inheritance
An object possesses properties and methods
A property is an attribute of an object
A method acts on an object
All JavaScript objects have toString() and valueOf() methods

HTML version of Basic Foils prepared 3 March 99

Foil 45 The Global Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Built-in Functions for Foil 45
The implicitly defined Global object is the top-level JavaScript object
It has two properties: NaN (Not-a-Number) and Infinity (but NN supports neither)
There are seven global functions:
plus the eval(...) function!

HTML version of Basic Foils prepared 3 March 99

Foil 46 The eval Function

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The eval() Function
The function eval( string ) invokes the JavaScript interpreter on its string argument, which is evaluated in the context of the current window (i.e., globally)
  • In NN3.0 only, we may also write: object.eval( string ) In this case, the string argument is evaluated in the context of some object
  • In NN4.0, the above is identical to: with (object) eval( string );

HTML version of Basic Foils prepared 3 March 99

Foil 47 Parsing Functions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Parsing Functions for Foil 47
parseInt(...) and parseFloat(...) convert their arguments to numbers: parseFloat("12.34"); //returns 12.34 parseInt("12.34"); //returns 12 parseFloat("12.34 ft"); //returns 12.34 parseInt("111", 2); //returns 7 parseFloat("$12.34"); //returns NaN
A handy trick: var numeric_var = string_val - 0;

HTML version of Basic Foils prepared 3 March 99

Foil 48 Other Global Functions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
isNaN( number ) returns true if and only if its argument is NaN
isFinite( number ) returns false if its argument is NaN, Infinity, or ?Infinity; otherwise, it returns true
escape( string ) returns a URL-encoded string; unescape( string ) performs the inverse operation

HTML version of Basic Foils prepared 3 March 99

Foil 49 Built-in Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Authoring Guide, Predefined Core Objects and Functions
JavaScript has ten built-in objects:
plus the Global object discussed earlier
An instance object is created with new:
  • var today = new Date();
  • var answers = new Array(0,1,0);
We will learn how to create objects in other ways later on e.g. fred = {}; creates a null object.

HTML version of Basic Foils prepared 3 March 99

Foil 50 Array Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Array Objects for Foil 50
In NN 3.0 (and even in 2.0!), we write: var states = new Array(50); states[0] = "Alabama"; states[1] = "Alaska"; // etc.
Every array has a length property: var n = states.length; // n = 2
Two-dimensional arrays are allowed: var acodes = new Array(50); acodes[0] = new Array(205,334);

HTML version of Basic Foils prepared 3 March 99

Foil 51 Array Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Array Methods
JavaScript 1.1 (and above) supports some powerful array methods:
  • myArray.sort( compFunc ) sorts myArray according to compFunc (a user-defined, numeric-valued function of two arguments) function compFunc( a, b ) { return a - b; }
  • myArray.join( sep ) returns a string of elements separated by sep
  • myArray.reverse() reverses the order of the elements in myArray

HTML version of Basic Foils prepared 3 March 99

Foil 52 Boolean Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Boolean Objects for Foil 52
To create a false Boolean object, use: new Boolean() new Boolean( 0 ) new Boolean( null ) new Boolean( "" ) new Boolean( false ) or simply use the literal false
All other values create a Boolean object with initial value true!

HTML version of Basic Foils prepared 3 March 99

Foil 53 Date Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The Date Object for Foil 53
The Date constructor has many forms: today = new Date(); xmas = new Date( 97, 12, 25 ); birthday = new Date( "April 6, 1952" );
  • The Date() constructor may also be used as a function with no arguments
  • Time measured in milliseconds past January 1, 1970 UTC (Universal Coordinated Time)
  • Warning: The Date object is buggy in NN2!

HTML version of Basic Foils prepared 3 March 99

Foil 54 Date Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Date Methods for Foil 54
The Date object has no properties; access to date and time fields is via dozens of "set" and "get" methods: xmas.setYear(xmas.getYear()+1);
There are two "static" Date methods:
  • Date.parse( date_string )
  • Date.UTC( year, month, day )
Both convert their argument(s) to milliseconds past January 1, 1970 UTC

HTML version of Basic Foils prepared 3 March 99

Foil 55 Function Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Function Objects for Foil 55
Every function statement gives rise to a Function object
Function objects are also created with the new operator: window.onload = new Function( "document.bgColor='white'" );
Function objects may be anonymous
NB: Function arguments are passed by value

HTML version of Basic Foils prepared 3 March 99

Foil 56 Function Arguments

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Functions may take an arbitrary number of arguments: function User() { this.name = User.arguments[0]; this.group = User.arguments[1]; this.email = new Array(); var n = User.arguments.length; for (var i = 2; i < n; i++) this.email[i-2]=User.arguments[i]; }
Note: the arguments[] array is built in

HTML version of Basic Foils prepared 3 March 99

Foil 57 The Math Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Math is the only built-in object that does not have a constructor
Its sole purpose is to provide constants (properties) and functions (methods)
The with statement is particularly useful in conjunction with Math: with ( Math ) { x = r*cos( PI/2 ); y = r*sin( PI/2 ); }

HTML version of Basic Foils prepared 3 March 99

Foil 58 Math Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Math Properties
These properties are primarily for convenience:

HTML version of Basic Foils prepared 3 March 99

Foil 59 Math Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Math Methods for Foil 59
Each method in the middle column requires two arguments

HTML version of Basic Foils prepared 3 March 99

Foil 60 Number Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
There is a Number constructor, but it is rarely used since JavaScript automatically converts numeric literals to numeric objects as needed
Some useful properties are provided: MAX_VALUE, MIN_VALUE, NaN, NEGATIVE_INFINITY, and POSITIVE_INFINITY

HTML version of Basic Foils prepared 3 March 99

Foil 61 Number Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Number.MIN_VALUE is the smallest positive number representable
Number.POSITIVE_INFINITY is returned by any operation that is greater than Number.MAX_VALUE
Number.NEGATIVE_INFINITY is returned by any operation that is less than ?Number.MAX_VALUE

HTML version of Basic Foils prepared 3 March 99

Foil 62 Number Properties (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Number.NaN is returned by parseInt(...) and parseFloat(...) when the parsing operation fails
An attempt to divide by zero also returns Number.NaN
Test for Number.NaN using the global boolean function isNaN()
Note: NN2.0 and MSIE3.0 do not support Number.NaN!

HTML version of Basic Foils prepared 3 March 99

Foil 63 Object Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
The Object constructor converts its argument (any numeric, boolean, or string literal) to a JavaScript object: var s = new Object( "NPAC" ); is equivalent to var s = new String( "NPAC" ); This is usually unnecessary, however
The corresponding function is Object(...)

HTML version of Basic Foils prepared 3 March 99

Foil 64 RegExp Objects I

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
An RegExp object (new in JavaScript 1.2) corresponds to a regular expression
  • Regular expressions were popular in Perl and JavaScript implementation is modeled on this version
There are two syntax's for defining regular expressions: regexp1 = new RegExp( "pattern" ); // or regexp1 = new RegExp( "pattern","flags" ); regexp2 = /pattern/flags; // no quotes
Flags are g (match to all occurences) and i (ignore case) or of course gi
The latter literal version "compiles" the pattern and is equivalent to
  • regexp2 = regexp1.compile("pattern")
  • Compilation is done for efficiency
The RegExp object has two other methods: exec(str) and test(str)and we can also invoke regular expression processing using new String object methods
There are both static (as in RegExp.input) and dynamic (as in regexp1.global) properties of regular expressions

HTML version of Basic Foils prepared 3 March 99

Foil 65 RegExp Objects II -- Examples

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index RegExp Object
Here are two examples: function isDigit( str ) { var regexp = /^[0-9]*$/; return regexp.test( str ); } function isSSN( str ) { // match 999999999 or 999-99-9999 var regexp = /^(\d{9}|\d{3}-\d{2}-\d{4})$/; return regexp.test( str ); }

HTML version of Basic Foils prepared 3 March 99

Foil 66 RegExp Objects III -- String Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Regular Expressions for Foil 66
String object methods have been added to JavaScript 1.2 to handle regular expressions -- consider an ordinary string ordstr
  • ordstr.search( regexp ); // like test(...)and equivalent to ordstr =~ m/regexp/ in PERL returns true or false
  • ordstr.match( regexp ); // like exec(...)and returns a results array as described for exec
  • newstr = oldstr.replace( regexp, newsubstr ); // equivalent to ordstr =~ s/regexp/newsubstr/ in PERL but returns a new string -- leaving original unchanged
The split(...) method now takes a regular expression as optional parameter:
  • var strArray = str.split( /\s*;\s*/ );
  • splits using ; surrounded by any whitespace characters

HTML version of Basic Foils prepared 3 March 99

Foil 67 Simple Regular Expression Patterns

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Simple Single-character Patterns are :
  • Single explicit character e.g. a
  • dot . which matches ANY character except newline \n
Character class is a Single-character Pattern and represented as a set [c1c2c3...cN] which matches any one of the listed characters
  • [ABCDE] matches A B C D or E
  • [0-9] is same as [0123456789]
  • [a-zA-Z] matches any lower or upper case letter
Negated character class is represented by a carat ^ after left [ square bracket
  • [^0-9] matches any character which is NOT a digit 0 1 2 3 4 5 6 7 8 9 (there is another critical use of ^ -- see later)
There are a set of special character classes shown overleaf such as \w which is equivalent to [A-Za-z0-9_].

HTML version of Basic Foils prepared 3 March 99

Foil 68 Regular Expressions -- Special Characters

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
[\b] backspace
\b Word Boundary
\B NOT a Word Boundary
\cC Control Character C
\d Matches a digit
\f Form Feed
\D Matches a NON digit
\n New Line
\s White Space \f\n\r\t\v
\r Carriage Return
\S Not a White Space
\t tab
\v vertical tab
\w Any word Character
\W Not a word Character
\\ Backslash itself
\n (n integer) nth () selected as in $n
\ooctal Char with this octal rep
\xhex Char with this hex rep
. Anything

HTML version of Basic Foils prepared 3 March 99

Foil 69 Grouping Patterns in Regular Expressions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Sequence is c1c2c3.. -- a sequence of single characters
* or {0,} is "zero or more" of previous character
+ or {1,} is "one or more" of previous character
? or {0,1} is "zero or one" of previous character
All matching is greedy -- they maximize number of characters "eaten up" starting with leftmost matching
Curly Brace Notation:
c{n1,n2} means from n1 to n2 instances of character c
c{n1,} means n1 or more instances of character c
c{n1} means exactly n1 instances of character c
c{0,n2} means n2 or less instances of character c

HTML version of Basic Foils prepared 3 March 99

Foil 70 Anchoring and Alternation in Regular Expressions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
For single characters, alternates can be specified by square brackets with
  • [abc] meaning a or b or c
For general strings one can use | to represent alternatives or so that above example can also be written
  • a|b|c means a or b or c but this operator can be generalized to longer sequences so that 1995 CPS616 (first year this course was taught!) instructor can be written
  • Fox|Furmanski or if we can't spell Polish names
  • Fox|Furmansk(i|y|ie) # See later for use of parentheses
Patterns can be Anchored in four ways:
  • /^Keyname:/ matches to Keyname: ONLY if it starts string -- ^ only has this special meaning at start of regular expression
  • /Quit$/ matches Quit ONLY if it ends string -- $ only has this meaning if at end of regular expression
  • \b matches a word(PERL/C variable) boundary so that
    • /Variable\b/ matches Variable but not Variables ( inside [] construct, \b means a backspace as described in earlier table)
  • \B matches NOT a word boundary so that
    • /Variable\B/ matches Variables but not Variable

HTML version of Basic Foils prepared 3 March 99

Foil 71 Parentheses in Regular Expressions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Parentheses can be used as "memory" for relating different parts of a match or for relating substitution to match
If a part of a regular expression is enclosed in parentheses, the MATCHED value is stored in temporary variables \1 \2 .. for first,second .. set of parentheses
  • /apple(,)\sorange\1/ matches apple, orange, in apple, orange, cherry, peach.
  • Note ONLY use \1 \2 etc. in pattern. Use $1 $2 (static properties of RegExp object) outside pattern
  • re1= /Geoffrey(.*)Fox/ when matched to str = "Geoffrey Charles Fox" stores
  • \1 = ' Charles ' which can be transferred to substitution string (via newstr = str.replace(re1,re2);) which could be
  • re2 = /Geoffrey \($1\) Fox/ for result Geoffrey ( Charles ) Fox
Parentheses can also be used to clarify meaning of a regular expression by defining precedence of a set of operations and so distinguish for instance
  • /(a|b)*/ from /a|(b*)/
  • There is a definite convention for precedence, but as usual I recommend using parentheses

HTML version of Basic Foils prepared 3 March 99

Foil 72 The Backslash \ Operator

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
  • re = new RegExp("\\w+")
  • re = /\w+/
For characters that are usually treated literally,\ indicates that the next character is special and not to be interpreted literally.
  • For example, /b/ matches the character b. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.
While for characters that are usually treated specially, \ indicates that the next character is not special and should be interpreted literally.
  • For example, * is a special character that means 0 or more occurrences of the preceding character should be matched;
  • For example, /a*/ means match 0 or more a's.
  • To match * literally, precede the it with a backslash;
  • For example, /a\*/ matches a*.

HTML version of Basic Foils prepared 3 March 99

Foil 73 Static Properties of RegExp Object I

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
RegExp.input or RegExp.$_ is text which we are comparing regular expression with
  • It is set automatically in some circumstances (e.g. when event handle for Form text field called as in example below)
  • <SCRIPT LANGUAGE="JavaScript1.2">
  • function getInfo() {
  • re = /(\w+)\s(\d+)/;
  • re.exec();
  • window.alert(RegExp.$1 + ", your age is " + RegExp.$2); }
  • </SCRIPT>
  • Enter your first name and your age, and then press Enter.
  • <FORM>
  • <INPUT TYPE:"TEXT" NAME="NameAge" onChange="getInfo(this);">
  • </FORM>

HTML version of Basic Foils prepared 3 March 99

Foil 74 Static Properties of RegExp Object II

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
RegExp.multiline if true, search through newlines
RegExp.$` or RegExp.leftContext is part of searched string before matched part
RegExp.$& or RegExp.lastMatch is part of searched string that is matched to by regular expression
RegExp.$' or RegExp.rightContext is part of searched string after matched part
So String searched is RegExp.leftContext + RegExp.lastMatch + RegExp.rightContext
RegExp.lastParen The last parenthesized substring match, if any
RegExp.$1,$2 .. $9 are the first through ninth parenthesized expressions matched

HTML version of Basic Foils prepared 3 March 99

Foil 75 Some Regular Expression Examples

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
/\s0(1+)/ matches "white space", followed by zero and 1 or more ones -- the set of ones is stored in \1 ( $1)
/[0-9]\.0\D/ matches "the answer is 1.0 exactly" but not "The answer is 1.00".
In first case $` is "the answer is ", $& is "1.0 " and $' is "exactly"
/a.*c.*d/ matches "axxxxcxxxxcdxxxxd" with $` and $' as null and $& as full string
/(a.*b)c.*d/ matches "axxxxbcxxxxbd" with
\1 as "axxxxb" -- note backtracking as greedy (a.*b) first matches to "axxxxbcxxxxb" but then tries again when following c.*d fails to match

HTML version of Basic Foils prepared 3 March 99

Foil 76 Examples of Replace and test

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT> // Prints out Smith, John
Suppose re is a RegExp object and str a string, then:
function testinput(re, str){
if (re.test(str))
midstring = " contains ";
else
midstring = " does not contain ";
document.write (str + midstring + re.source);
}
Prints out a summary of matching result

HTML version of Basic Foils prepared 3 March 99

Foil 77 Examples of match (string) and exec (RegExp)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
//Match one d followed by one or more b's followed by one d
//Remember matched b's and the following d
myRe=/d(b+)(d)/ig; str = "cdbBdbsbz";
myArray = myRe.exec( str );
myArray.index Index of First Character Matched i.e. 1
myArray.input The original String i.e. cdbBdbsbz
myArray[0] The characters matched i.e. dbBd
myArray[1] The first parenthesis i.e. bB
myArray[2] The second parenthesis i.e. d
The static properties of RegExp are set including $` $& $' $1 $2 lastMatch lastParen
Properties source lastIndex multiline global ignoreCase of myRe are also set
Can also use myArray = str.match(myRe)

HTML version of Basic Foils prepared 3 March 99

Foil 78 Multiple Calls to exec Method

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
If your regular expression uses the g flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property. For example, assume you have this script:
<SCRIPT LANGUAGE="JavaScript1.2">
myRe=/ab*/g;
str = "abbcdefabh"
myArray = myRe.exec(str);
document.writeln("Found " + myArray[0] + ". Next match starts at " + myRe.lastIndex)
mySecondArray = myRe.exec(str);
document.writeln("Found " + mySecondArray[0] + ". Next match starts at " + myRe.lastIndex)
</SCRIPT>
This script displays the following text:
Found abb. Next match starts at 3
Found ab. Next match starts at 9

HTML version of Basic Foils prepared 3 March 99

Foil 79 String Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
String objects are created as in var myStr = new String("NPAC"); or more simply with var myStr = "NPAC";
Actually, the latter is a string literal, but these are automatically converted as needed
String characters are indexed starting with 0
The String object has one property: var n = myStr.length;

HTML version of Basic Foils prepared 3 March 99

Foil 80 String Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index String Methods for Foil 80
Core JavaScript String methods:
  • charAt( pos )
  • charCodeAt( pos )
  • indexOf( searchstring, pos )
  • lastIndexOf( searchstring, pos )
  • split( separator )
  • substring( start, end )
  • toLowerCase() and toUpperCase()
Static method: String.fromCharCode(...)

HTML version of Basic Foils prepared 3 March 99

Foil 81 String Methods (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Client-side JavaScript defines more than a dozen String methods (discussed later)
Six new methods added in JavaScript 1.2:
  • concat( string2 )
  • match( regexp )
  • replace( regexp, newSubstr )
  • search( regexp )
  • slice( begSlice, endSlice )
  • substr( start, length )

HTML version of Basic Foils prepared 3 March 99

Foil 82 JavaScript Events

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 83 Events

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Authoring Guide, Handling Events
Events are associated with
  • forms
  • hyperlinks
  • images and image maps
  • loading and unloading of documents
  • input focus of a window or form element
JavaScript introduces event handlers to handle these events

HTML version of Basic Foils prepared 3 March 99

Foil 84 Event Handlers

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Event Handlers for Foil 84

HTML version of Basic Foils prepared 3 March 99

Foil 85 Event Handlers (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Event Handlers for Foil 85

HTML version of Basic Foils prepared 3 March 99

Foil 86 Event Handlers (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index New Event Handlers for Foil 86
JavaScript 1.2 adds ten new event handlers
Three existing handlers (onClick, onMouseOut, and onMouseOver) have new properties
All these events are supported by IE4.0 except onDragDrop

HTML version of Basic Foils prepared 3 March 99

Foil 87 Event Handler Examples

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
The onLoad event handler is triggered when a page is loaded or reloaded : <BODY onLoad="init()"> Similarly, the onUnload handler is called when a page is exited
Here's another example:
<FORM
onSubmit="return check(this)">
...
</FORM>

HTML version of Basic Foils prepared 3 March 99

Foil 88 Event Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The Event Object
An Event object (new in JavaScript 1.2) is passed to an event handler when an event occurs
There are 23 types of events, one for each handler: for example, a Click event is passed to the onClick handler when a link or form element is clicked
An Event object has up to 11 properties

HTML version of Basic Foils prepared 3 March 99

Foil 89 Event Object (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The Event Object for Foil 89
Properties of an Event object:
The Click object, for example, supports all but the data property (note: the *X and *Y properties are undefined for button clicks)

HTML version of Basic Foils prepared 3 March 99

Foil 90 Client-side JavaScript

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 91 Object Hierarchy

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Authoring Guide, Using Navigator Objects

HTML version of Basic Foils prepared 3 March 99

Foil 92 Object Referencing

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Object Referencing
A fully-qualified reference: window.document.myForm.myButton.value
window (often suppressed) and document are pre-defined objects
myForm and myButton are user-defined object names
value is a property of the Button object (and most other form elements)

HTML version of Basic Foils prepared 3 March 99

Foil 93 Window and Frame Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Authoring Guide, Using Windows and Frames
A Window object--the top-level JavaScript object--is the reflection of a <BODY> or <FRAMESET> tag
A browser window may be divided into subwindows called frames
A Frame object--the reflection of a <FRAME> tag--"inherits" all of its properties and methods from the Window object

HTML version of Basic Foils prepared 3 March 99

Foil 94 Window Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Window Properties for Foil 94
window and self are synonyms for the current window
top refers to the highest-level window in a hierarchy of frames
parent refers to the previous window or frame in a hierarchy of frames
A window may have a name: myWin = window.open(URL);
Note: The opener property is not supported in NN2.

HTML version of Basic Foils prepared 3 March 99

Foil 95 Window Properties (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
An analogy with the UNIX shell:

HTML version of Basic Foils prepared 3 March 99

Foil 96 Frame Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Frame Properties for Foil 96
A Frame object also has properties called window, self, and parent
The most important property of the Frame object is the frames[] array
Each <FRAME> tag automatically creates an entry in the frames[] array
Frames may also have names, as in <FRAME NAME="upperFrame">

HTML version of Basic Foils prepared 3 March 99

Foil 97 Frame Example

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
<!-- File: index.html -->
<HTML>
<FRAMESET ROWS="90%,10%">
<FRAME SRC="skeleton.html"
NAME="upperFrame">
<FRAME SRC="navigate.html"
NAME="navigateFrame">
</FRAMESET>
<NOFRAMES>...</NOFRAMES>
</HTML>

HTML version of Basic Foils prepared 3 March 99

Foil 98 Frame Example (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
<!-- File: skeleton.html --> <HTML> <FRAMESET ROWS="30%,70%"> <FRAME SRC="category.html" NAME="listFrame"> <FRAME SRC="titles.html" NAME="contentFrame"> </FRAMESET> </HTML>

HTML version of Basic Foils prepared 3 March 99

Foil 99 Frame Example (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Absolute references:
  • top.navigateFrame
  • top.upperFrame
  • top.upperFrame.contentFrame
  • top.upperFrame.listFrame
Relative references:
  • parent.upperFrame
  • parent.contentFrame
  • parent.parent.navigateFrame
In which documents are
these references valid?

HTML version of Basic Foils prepared 3 March 99

Foil 100 Frameset Documents

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Frameset Documents for Foil 100
The <FRAMESET> and <BODY> tags are mutually exclusive
No closing tag for <FRAME> is needed
A frameset document may contain a <SCRIPT> in its <HEAD>
Use <NOFRAMES> inside <FRAMESET> for frames-impaired browsers

HTML version of Basic Foils prepared 3 March 99

Foil 101 Window and Frame Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Window and Frame Methods for Foil 101
Both Window and Frame objects have blur, focus, clearTimeout, and setTimeout methods
The Window object also has alert, close, confirm, open, and prompt methods. For example, var msg = "The alert() method\n"; msg += " is handy for debugging."; window.alert( msg );

HTML version of Basic Foils prepared 3 March 99

Foil 102 History Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index History Properties and Methods for Foil 102
There is one History (and Location) object per window or frame
The History object is essentially an array of URLs (called history[]), which most browsers restrict access to
Two methods back() and forward() perform the same functions as the corresponding browser buttons

HTML version of Basic Foils prepared 3 March 99

Foil 103 Location Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The Location Object for Foil 103
The Location object corresponds to the URL of the current document
To load a new document into the current window, use: window.location.href = "foo.html"; or simply window.location = "foo.html";
Location object properties: href, protocol, host, pathname, search

HTML version of Basic Foils prepared 3 March 99

Foil 104 Document Object

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Document Properties for Foil 104
There is one Document object (called document) per window or frame
The Document object has numerous subobjects (Anchor, Applet, Embed, Area, Form, Image, Link, Layer) and property arrays (anchors[], applets[], embeds[], forms[], images[], links[], layers[])

HTML version of Basic Foils prepared 3 March 99

Foil 105 Document Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
A Document object has the following color properties: alinkColor, linkColor, vlinkColor, bgColor, and fgColor
Other Document properties include lastModified and URL: with ( document ) { writeln('<TT>', URL, '</TT><BR>'); writeln('Updated: ', lastModified); }

HTML version of Basic Foils prepared 3 March 99

Foil 106 Document Properties (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Document Properties
To list the properties of document: for ( var prop in document ) { with ( document ) { write( prop + " = " ); writeln( eval(prop), "<BR>"); } }
Recall that the with statement qualifies all object references within its scope

HTML version of Basic Foils prepared 3 March 99

Foil 107 Document Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Document Methods for Foil 107
The write(...) and writeln(...) methods take a comma-separated list of string expressions
The open() and close() methods (not to be confused with window.open() and window.close()) open and close a document for writing, but these are seldom used explicitly

HTML version of Basic Foils prepared 3 March 99

Foil 108 Form Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Form Objects for Foil 108
Every Form object is the reflection of an HTML <FORM> tag
The forms[] array may be indexed by integer or name (i.e., forms[0] or forms['myForm'] )
A Form object has many subobjects, each corresponding to an HTML form element. These are reflected in the elements[] array

HTML version of Basic Foils prepared 3 March 99

Foil 109 Form Properties

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index The form Property
Form elements are reflected in the elements[] array. For example, document.forms[0].elements[1]; is the second element of the first form
Most Form properties (action, encoding, method, and target) are read/write variables, that is, these properties may be modified on-the-fly

HTML version of Basic Foils prepared 3 March 99

Foil 110 Form Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Invoking the submit() or reset() method on a Form object has the same effect as pressing the corresponding button
The event handlers onSubmit and onReset may be used to override the default submit and reset actions.

HTML version of Basic Foils prepared 3 March 99

Foil 111 Image Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Image Objects
Images may be pre-loaded (they should be cached in the <HEAD>, especially if they are to be used in the <BODY>): var images = new Array( num ); for ( var i = 0; i < num; i++ ) { images[i] = new Image(); images[i].src = "image"+ i +".gif"; }
This code loads files "image1.gif", "image2.gif", and so on

HTML version of Basic Foils prepared 3 March 99

Foil 112 Image Animation

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Animation for Foil 112
Now suppose we have the tag <IMG NAME=img> in the <BODY>. The following recursive method animates the cached images: var n = 0; function animate() { document.img.src = images[n].src; n = (n + 1) % images.length; id = setTimeout("animate()", 250); }

HTML version of Basic Foils prepared 3 March 99

Foil 113 Layer Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Layers for Foil 113
Think of a Layer object (new in JS 1.2) as a dynamic document within a document
Each <LAYER> tag generates a Layer object and a corresponding element in the layers[] array
Layers have many methods and properties (most of which may be modified on-the-fly)
Note: Layers are not supported in MSIE

HTML version of Basic Foils prepared 3 March 99

Foil 114 Built-in Arrays

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
JavaScript has numerous built-in arrays, each with its own length property:
Plus the history array--the only one whose name does not end in "s"!

HTML version of Basic Foils prepared 3 March 99

Foil 115 HTML-reflected Arrays

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Plus the elements array, whose parent is the Form object

HTML version of Basic Foils prepared 3 March 99

Foil 116 Client-side String Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Client-side String Methods for Foil 116
Client-side JavaScript defines more than a dozen String methods, including:

HTML version of Basic Foils prepared 3 March 99

Foil 117 Navigator Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Navigator Object for Foil 117
The Navigator object contains information about the browser
Two properties are appName and appVersion
Methods include javaEnabled and taintEnabled
All windows share the same Navigator object, which is truly global

HTML version of Basic Foils prepared 3 March 99

Foil 118 MimeType Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Displaying All MimeType Objects
The MimeType object is a subobject of the Navigator object
The mimeTypes[] array contains an entry for each MIME type supported by the browser
Properties of MimeType include description, type, and suffixes
The property enabledPlugin refers to a Plugin object

HTML version of Basic Foils prepared 3 March 99

Foil 119 Plugin Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index Plugins for Foil 119
Like MimeType, the Plugin object is a subobject of the Navigator object
The plugins[] array contains an entry for each installed plugin
Each Plugin object is an array of MimeType objects. For example, navigator.plugins[0][0].type is a MIME type supported by plugins[0]

HTML version of Basic Foils prepared 3 March 99

Foil 120 JavaScript Object Model

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index

HTML version of Basic Foils prepared 3 March 99

Foil 121 How to define Objects in JavaScript

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
We can use constructors described later but simplest way is:
newobject ={};
newobject.car = "honda";
newobject.wheels = 4;
newobject.color = "red";
Or newobject={car:"honda",wheels:4,color:"red"};
Or newobject = new Array();
newobject["car"] = "honda"; // etc.
This allows an "associative array"

HTML version of Basic Foils prepared 3 March 99

Foil 122 User-defined Objects

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Objects are defined with the function statement. The following Circle object, for example, has property r: function Circle( r ) { this.r = ( r > 0 ) ? r : 0; }
The this keyword permits this function to be used as a constructor: var c = new Circle( 2.0 ); var area = Math.PI * c.r * c.r;

HTML version of Basic Foils prepared 3 March 99

Foil 123 User-defined Methods

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Methods are defined as Function objects: function Circle( r ) { this.r = ( r > 0 ) ? r : 0; this.getRadius = new Function( "return this.r" ); this.setRadius = new Function( "r", "this.r = r" ); }
Note: The last argument of the Function constructor is implicitly the method body

HTML version of Basic Foils prepared 3 March 99

Foil 124 Another Example

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Here's another example: function Car( make, model ) { this.make = make || ""; this.model = model || ""; this.color = null; this.setColor = new Function( "color", "this.color = color" ); }
Instantiate a Car object with new: myCar = new Car( "Ford", "Explorer" ); myCar.setColor( "red" );

HTML version of Basic Foils prepared 3 March 99

Foil 125 The prototype Property

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Methods may be added after the fact: function Circle_area() { return Math.PI * this.r * this.r; } Circle.prototype.area = Circle_area;
Use the previous method as follows: var radius = 1/Math.sqrt( Math.PI ); var c = new Circle( radius ); var area = c.area();

HTML version of Basic Foils prepared 3 March 99

Foil 126 The prototype Property (cont'd)

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
We can add methods to built-in objects, too: // Does an array contain element x ? function contains( x ) { for (var i=0; i<this.length; i++) { if (this[i] == x) return true; } return false; }
Now add the method to the Array object with the prototype property: Array.prototype.contains = contains;

HTML version of Basic Foils prepared 3 March 99

Foil 127 Prototype-based Inheritance

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. *
Full HTML Index
Define the parent object: function Ellipse( r1, r2 ) { this.r1 = ( r1 > 0 ) ? r1 : 0; this.r2 = ( r2 > 0 ) ? r2 : 0; this.area = new Function( "return Math.PI * this.r1 * this.r2" ); }
Define the child object: function Circle( r ) { this.r = ( r > 0 ) ? r : 0; this.parent = Ellipse; this.parent( r, r ); } Circle.prototype = new Ellipse;

© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Wed Mar 3 1999