21 Javascript
21 Javascript
Language Fundamentals
3
JavaScript isn’t always available
Some old browsers do not recognize script tags
These browsers will ignore the script tags but will display the included
JavaScript
To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
The <!-- introduces an HTML comment
To get JavaScript to ignore the HTML close comment, -->, the // starts a
JavaScript comment, which extends to the end of the line
Some users turn off JavaScript
Use the <noscript>message</noscript> to display a message in place of
whatever the JavaScript would put there
4
Where to put JavaScript
JavaScript can be put in the <head> or in the <body> of an
HTML document
JavaScript functions should be defined in the <head>
This ensures that the function is loaded before it is needed
6
Variables
8
Operators, II
String operator:
+
The conditional operator:
condition ? value_if_true : value_if_false
Special equality tests:
== and != try to convert their operands to the same type
before performing the test
=== and !== consider their operands unequal if they are of
different types
Additional operators (to be discussed):
new typeof void delete
9
Comments
Comments are as in C or Java:
Between // and the end of the line
Between /* and */
Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript
10
Statements, I
11
Statements, II
The switch statement:
switch (expression) {
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
Other familiar statements:
break;
continue;
The empty statement, as in ;; or { }
12
JavaScript is not Java
By now you should have realized that you already know a
great deal of JavaScript
So far we have talked about things that are the same as in Java
JavaScript has some features that resemble features in Java:
JavaScript has Objects and primitive data types
JavaScript has qualified names; for example,
document.write("Hello World");
JavaScript has Events and event handlers
Exception handling in JavaScript is almost the same as in Java
JavaScript has some features unlike anything in Java:
Variable names are untyped: the type of a variable depends on the
value it is currently holding
Objects and arrays are defined in quite a different way
JavaScript has with statements and a new kind of for statement
13
Exception handling, I
Exception handling in JavaScript is almost the same as in Java
throw expression creates and throws an exception
The expression is the value of the exception, and can be of any type
(often, it's a literal String)
try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception handling statements
} finally { // optional, as usual
code that is always executed
}
With this form, there is only one catch clause
14
Exception handling, II
try {
statements to try
} catch (e if test1) {
exception handling for the case that test1 is true
} catch (e if test2) {
exception handling for when test1 is false and test2 is true
} catch (e) {
exception handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
Typically, the test would be something like
e == "InvalidNameException"
15
Object literals
You don’t declare the types of variables in JavaScript
JavaScript has object literals, written with this syntax:
{ name1 : value1 , ... , nameN : valueN }
special
"Saturn" and "Mazda" are Strings
16
Three ways to create an object
You can use an object literal:
var course = { number: "CIT597", teacher: "Dr. Dave" }
You can use new to create a “blank” object, and add fields to it
later:
var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
You can write and use a constructor:
function Course(n, t) { // best placed in <head>
this.number = n; // keyword "this" is required, not optional
this.teacher = t;
}
var course = new Course("CIT597", "Dr. Dave");
17
Array literals
You don’t declare the types of variables in JavaScript
JavaScript has array literals, written with brackets and
commas
Example: color = ["red", "yellow", "green", "blue"];
Arrays are zero-based: color[0] is "red"
If you put two commas in a row, the array has an
“empty” element in that location
Example: color = ["red", , , "green", "blue"];
color has 5 elements
However, a single comma at the end is ignored
Example: color = ["red", , , "green", "blue”,]; still has 5 elements
18
Four ways to create an array
You can use an array literal:
var colors = ["red", "green", "blue"];
You can use new Array() to create an empty array:
var colors = new Array();
You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
You can use new Array(n) with a single numeric
argument to create an array of that size
var colors = new Array(3);
You can use new Array(…) with two or more arguments
to create an array containing those values:
var colors = new Array("red","green", "blue");
19
The length of an array
20
Arrays and objects
Arrays are objects
car = { myCar: "Saturn", 7: "Mazda" }
car[7] is the same as car.7
car.myCar is the same as car["myCar"]
If you know the name of a property, you can use dot
notation: car.myCar
If you don’t know the name of a property, but you have
it in a variable (or can compute it), you must use array
notation: car["my" + "Car"]
21
Array functions
If myArray is an array,
myArray.sort() sorts the array alphabetically
myArray.sort(function(a, b) { return a - b; }) sorts
numerically
myArray.reverse() reverses the array elements
myArray.push(…) adds any number of new elements to the
end of the array, and increases the array’s length
myArray.pop() removes and returns the last element of the
array, and decrements the array’s length
myArray.toString() returns a string containing the values of
the array elements, separated by commas
22
The for…in statement
You can loop through all the properties of an object with
for (variable in object) statement;
Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
Possible output: teacher: Dr. Dave
number: CIT597
The properties are accessed in an undefined order
If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
Notice that course["teacher"] is equivalent to course.teacher
You must use brackets if the property name is in a variable
23
The with statement
with (object) statement ; uses the object as the default
prefix for variables in the statement
For example, the following are equivalent:
with (document.myForm) {
result.value = compute(myInput.value) ;
}
document.myForm.result.value =
compute(document.myForm.myInput.value);
One of my books hints at mysterious problems resulting
from the use of with, and recommends against ever
using it
24
Functions
Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
The syntax for defining a function is:
function name(arg1, …, argN) { statements }
The function may contain return value; statements
Any variables declared within the function are local to it
The syntax for calling a function is just
name(arg1, …, argN)
Simple parameters are passed by value, objects are
passed by reference
25
Regular expressions
A regular expression can be written in either of two ways:
Within slashes, such as re = /ab+c/
With a constructor, such as re = new RegExp("ab+c")
Regular expressions are almost the same as in Perl or Java (only
a few unusual features are missing)
string.match(regexp) searches string for an occurrence of
regexp
It returns null if nothing is found
If regexp has the g (global search) flag set, match returns an array of
matched substrings
If g is not set, match returns an array whose 0th element is the matched
text, extra elements are the parenthesized subexpressions, and the index
property is the start position of the matched substring
26
Warnings
JavaScript is a big, complex language
We’ve only scratched the surface
It’s easy to get started in JavaScript, but if you need to use it
heavily, plan to invest time in learning it well
Write and test your programs a little bit at a time
JavaScript is not totally platform independent
Expect different browsers to behave differently
Write and test your programs a little bit at a time
Browsers aren’t designed to report errors
Don’t expect to get any helpful error messages
Write and test your programs a little bit at a time
27
Evaluation (i.e., Dave’s opinion)
JavaScript, like Java, is in the C family of languages
JavaScript has lots of convenience features
Global variables
Not having to declare variables at all
Untyped variables
Easy modification of objects
JavaScript is designed for programming in the small, not for
large programs
Many features, such as global variables, are bad news for large programs
My experience is that JavaScript is very nice if you use it for the
purposes that its designers expected, but very ugly if you try to
use it in non-routine ways
28
The End
29
More JavaScript
31
What you can’t do
To protect the visitor to your web pages, you can’t:
Read or write user files
However, JScript on IE allows ASP scripting, which is how the very
destructive JS.Gigger.A@mm worm spreads
To turn off active scripting in Outlook Express, see
http://support.microsoft.com/support/kb/articles/Q192/8/46.ASP
Execute any other programs
Connect to any other computer, except to download another
HTML page or to send e-mail
Determine what other sites the user has visited
Open a very small (less than 100px by 100px) window or an
offscreen window (except in IE)
32
Debugging
Mozilla/Netscape has much better debugging tools than IE
Mozilla
Select Tools => Web Development => JavaScript console
Netscape 6:
Select Tasks => Tools => JavaScript console
Netscape 4:
Select Communicator => Tools => JavaScript console
Any Mozilla or Netscape:
Type javascript: in the location bar and press Enter
Internet Explorer:
Go to the Preferences... dialog and look for something like Web
content => Show scripting error alerts
After debugging, test your program in IE
IE is the most popular browser
33
Numbers
In JavaScript, all numbers are floating point
Special predefined numbers:
Infinity, Number.POSITIVE_INFINITY -- the result of dividing a positive
number by zero
Number.NEGATIVE_INFINITY -- the result of dividing a negative number
by zero
NaN, Number.NaN (Not a Number) -- the result of dividing 0/0
NaN is unequal to everything, even itself
There is a global isNaN() function
Number.MAX_VALUE -- the largest representable number
Number.MIN_VALUE -- the smallest (closest to zero) representable
number
34
Strings and characters
In JavaScript, string is a primitive type
Strings are surrounded by either single quotes or double quotes
There is no “character” type
Special characters are:
35
Some string methods
charAt(n)
Returns the nth character of a string
concat(string1, ..., stringN)
Concatenates the string arguments to the recipient string
indexOf(substring)
Returns the position of the first character of substring in the recipient
string, or -1 if not found
indexOf(substring, start)
Returns the position of the first character of substring in the given string
that begins at or after position start, or -1 if not found
lastIndexOf(substring), lastIndexOf(substring, start)
Like indexOf, but searching starts from the end of the recipient string
36
More string methods
match(regexp)
Returns an array containing the results, or null if no match is found
On a successful match:
groups
The array index property gives the first matched position
replace(regexp, replacement)
Returns a new string that has the matched substring replaced with
the replacement
search(regexp)
Returns the position of the first matched substring in the given
38
undefined and null
There are special values undefined and null
undefined is the only value of its “type”
This is the value of a variable that has been declared but not
defined, or an object property that does not exist
void is an operator that, applied to any value, returns the
value undefined
null is an “object” with no properties
null and undefined are == but not ===
39
Arrays
As in C and Java, there are no “true”
multidimensional arrays
However, an array can contain arrays
The syntax for array reference is as in C and Java
Example:
var a = [ ["red", 255], ["green", 128] ];
var b = a[1][0]; // b is now "green"
var c = a[1]; // c is now ["green", 128]
var d = c[1]; // d is now 128
40
Determining types
The unary operator typeof returns one of the following
strings: "number", "string", "boolean", "object",
"undefined", and "function"
typeof null is "object"
If myArray is an array, typeof myArray is "object"
To distinguish between different types of objects,
myObject instanceof Constructor
The Constructor should be an object that is a constructor function
It is an error if the right-hand side is not an object at all
myObject.constructor == Constructor
myObject.toString() == "ConstructorName"
41
Wrappers and conversions
JavaScript has “wrapper” objects for when a primitive value must
be treated as an object
var s = new String("Hello"); // s is now a String
var n = new Number(5); // n is now a Number
var b = new Boolean(true); // b is now a Boolean
Because JavaScript does automatic conversions as needed, wrapper
objects are hardly ever needed
JavaScript has no “casts,” but conversions can be forced
var s = x + ""; // s is now a string
var n = x + 0; // n is now a number
var b = !!x; // b is now a boolean
Because JavaScript does automatic conversions as needed, explicit
conversions are hardly ever needed
42
Variables
Every variable is a property of an object
When JavaScript starts, it creates a global object
In client-side JavaScript, the window is the global
object
It can be referred to as window or as this
The “built-in” variables and methods are defined here
There can be more than one “global” object
For example, one frame can refer to another frame with
code such as parent.frames[1]
Local variables in a function are properties of a
special call object
43
HTML names in JavaScript
In HTML the window is the global object
It is assumed that all variables are properties of this
object, or of some object descended from this object
The most important window property is document
HTML form elements can be referred to by
document.forms[formNumber].elements[elementNumber]
Every HTML form element has a name attribute
The name can be used in place of the array reference
Hence, if
<form name="myForm">
<input type="button" name="myButton" ...>
Then instead of document.forms[0].elements[0]
you can say document.myForm.myButton
44
More about with
with (object) statement ; uses the object as the default
prefix for variables in the statement
As noted in an earlier lecture, one book hints at
mysterious problems resulting from the use of with,
and recommends against ever using it
It turns out that there are two problems:
with is difficult to optimize, hence may be inefficient
More importantly, variable declarations and function
definitions have odd and counterintuitive behavior
The problem appears to be determining if the prefix is used
Other types of statements are fine
45
Functions
In Java, methods are associated with objects
In JavaScript, a function is an object
Functions can be recursive:
function factorial(n) {
if (n <= 1) return 1;
else return n * factorial(n - 1);
}
Functions can be nested:
function hypotenuse(a, b) {
function square(x) { return x * x; }
return Math.sqrt(square(a) + square(b));
}
46
The Function() constructor
Since functions are objects, they have a constructor:
Function(arg1, arg2, ..., argN, body)
All the arguments to the constructor are strings
Example:
var f = new Function("x", "y", "return x * y;");
Notice that the function has no name
But you can assign it to a variable and use that name
The name can be used to call the function as usual
You can construct functions dynamically in JavaScript
(they are automatically compiled)
However, compilation is computationally expensive
Functions defined in this way are always global
47
Function literals
As we just saw, a function can be defined by means of a
constructor:
var f = new Function("x", "y", "return x * y;");
A function can be written literally, as in the following
example:
var f = function(x, y) { return x * y; }
This function is not necessarily global
To write a recursive literal function, give it a name:
var f = function fact(n) { if (n <= 1) return n;
else return n * fact(n - 1) ; };
The name does not persist after the function is created
48
Function names
The “name” of a function is just the variable that holds
the function
var square = function(x) { return x * x; };
var a = square(4); // a now holds 16
var b = square; // b now holds square
var c = b(5); // c now holds 25
var d = [ b ]; // d is an array
var e = d[0](6); // e now holds 36
49
The call object
When a function is called, a new call object
is created
The properties of the call object include:
The function parameters
Local variables declared with the var statement
The arguments object
50
arguments
The arguments object is like an array
arguments[n] is a synonym for the nth argument
arguments.length is the number of arguments
that the function was called with
function.length is the number of arguments it was
defined with
arguments.length, unlike function.length, is
available only within the function
arguments.callee is the function itself
51
Example uses of arguments
function max() {
var m = Number.NEGATIVE_INFINITY;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] > m) m = arguments[i];
}
return m;
}
function(n) {
if (n <= 1) return 1;
return n * arguments.callee(n - 1);
}
52
Methods
When a function is a property of an object, we call it a
“method”
A method can be invoked by either of
call(object, arg1, ..., argN) or
apply(object, [arg1, ..., argN])
call and apply are defined for all functions
call takes any number of arguments
apply takes an array of arguments
Both allow you to invoke a function as if it were a method of
some other object, object
Inside the function, the keyword this refers to the object
53
Properties of functions
Since a function is an object, you can add properties
to it
Function properties are often a good alternative to global
variables
Example:
uniqueInteger.counter = 0;
function uniqueInteger() {
return uniqueInteger.counter++;
}
Function properties are a bit like static variables in Java
54
The End
55
JavaScript and HTML
57
Events
Some (but not all) elements on the web page respond to
user interactivity (keystrokes, mouse clicks) by creating
events
Different kinds of elements produce different events
Browsers are not all alike in what events are produced
We will concentrate on events from HTML form elements
and commonly recognized events
You can put handlers on HTML form elements
If the event isn’t generated, the handler does nothing
A handler should be very short
Most handlers call a function to do their work
58
A simple event handler
<form method="post" action="">
<input type="button"
name="myButton"
value="Click me"
onclick="alert('You clicked the button!');">
</form>
The button is enclosed in a form
59
Capitalization
JavaScript is case sensitive
HTML is not case sensitive
onclick="alert('You clicked the button!');"
The underlined parts are HTML
The quoted string is JavaScript
You will frequently see onclick capitalized as onClick
The Java naming convention is easier to read
This is fine in HTML, but an error if it occurs in JavaScript
61
Example: Simple rollover
The following code will make the text Hello
red when the mouse moves over it, and
blue when the mouse moves away
<h1 onMouseOver="style.color='red';"
onMouseOut="style.color='blue';">Hello </h1>
Image rollovers are just as easy:
<img src="../Images/duke.gif"
width="55" height="68"
onMouseOver="src='../Images/duke_wave.gif';"
onMouseOut="src='../Images/duke.gif';">
62
Events and event handlers I
The following tables are taken from:
http://developer.netscape.com/docs/manuals/js/client/
jsguide/index.htm
66
Events and event handlers V
67
Events and event handlers VI
69
The DOM
hierarchy
Source:
http://sislands.com/coin70/week1/dom.htm
70
Fields of window, I
window
The current window (not usually needed).
self
Same as window.
parent
If in a frame, the immediately enclosing window.
top
If in a frame, the outermost enclosing window.
frames[ ]
An array of frames (if any) within the current window. Frames are
themselves windows.
length
The number of frames contained in this window.
71
Fields of window, II
document
The HTML document being displayed in this window.
location
The URL of the document being displayed in this window. If you set this
property to a new URL, that URL will be loaded into this window. Calling
location.reload() will refresh the window.
navigator
A reference to the Navigator (browser) object. Some properties of
Navigator are:
appName -- the name of the browser, such as "Netscape"
platform -- the computer running the browser, such as "Win32"
status
A read/write string displayed in the status area of the browser window.
Can be changed with a simple assignment statement.
72
Methods of window, I
alert(string)
Displays an alert dialog box containing the string and an OK
button.
confirm(string)
Displays a confirmation box containing the string along with
Cancel and OK buttons. Returns true if OK is pressed, false if
Cancel is pressed.
prompt(string)
Displays a confirmation box containing the string, a text field,
and Cancel and OK buttons. Returns the string entered by the
user if OK is pressed, null if Cancel is pressed.
73
Methods of window, II
open(URL)
Opens a new window containing the document specified by
the URL.
close()
Closes the given window (which should be a top-level
window, not a frame).
74
Fields of document, I
You must prefix these fields with document.
anchors[ ]
An array of Anchor objects (objects representing
<a name=...> tags)
applets[ ]
An array of Applet objects
The properties are the public fields defined in the applet
The methods are the public methods of the applet
Cautions:
You must supply values of the correct types for the fields
75
Fields of document, II
forms[ ]
An array of Form elements
If the document contains only one form, it is forms[0]
images[ ]
An array of Image objects
To change the image, assign a new URL to the src property
links[ ]
An array of Link objects
A link has several properties, including href, which holds the
complete URL
76
Fields of document, III
bgColor
The background color of the document
May be changed at any time
title
A read-only string containing the title of the document
URL
A read-only string containing the URL of the document
77
Fields of the form object
elements[ ]
An array of form elements
78
The End
79