Transcript JavaScript

XP
JavaScript
•
•
•
Source from multiple external sources from the
Internet over the years
Please PM me to claim credit if needed
Known Arthur: John Mitchell (2008), Tom Horton,
Alfred C Weaver, Richard Sinn
1
XP
JavaScript History
 Developed by Brendan Eich at Netscape
 Scripting language for Navigator 2
 Later standardized for browser compatibility
 ECMAScript Edition 3 (aka JavaScript 1.5)
 Related to Java in name only
 Name was part of a marketing deal
 Various implementations available
 Spidermonkey interactive shell interface
 Rhino: http://www.mozilla.org/rhino/
XP
HTML Background
 Many “markup” languages in the past
 SGML: Standard Generalized Markup
Language
 HTML (Hypertext Markup Language) based on
SGML
 XML (eXtensible Markup Language)
“replaces” SGML
 XHTML is replacing HTML
3
XP
Principles
 Distinguish structure from presentation
 Presentation based on structure
 Presentation may vary, perhaps based on display
characteristics, user-preference, etc.
 People like to ignore this idea
 E.g. use <B> vs. <EM>
 <font> tag?
 XML and CSS or XSL
4
XP
5
XP
Tags and Elements
 Example of an element:
<name attr1=“attrval”>content</name>
 Begin and end tags set off a section of a
document
 Has a semantic property by tag-name
 Modified by attributes
 “content” can contain other elements
 Elements nest, don’t “overlap”
 Empty-elements: no end tag
 <br /> <img … />
 Note space before />
6
XP
Basic HTML Structure
 Comments:
<!-- … -->
 Example:
<html>
<head>
…
</head>
<body>
….
</body>
</html>
<--- title, metatags, etc. (not
displayed)
<--- main content
(displayed)
7
XP
Larger Example
<html>
<head>
<title>An Example</title>
</head>
<body>
<h3><hr>An Example</h3>
<p align="left">
<font face="Comic Sans MS"
size="4"><b>
Hello World!</b></font>
</p>
<p align="right">
<font size="5"><u>I am
21.</u></font>
</p>
<!-- see next column -->
<p>
<ol type="I" start=7>
<li><font
color=#00FF00>Green</fo
nt></li>
<li>Yellow</li>
<ul type=square>
<li>John</li>
<li>Mike</li>
</ul>
</ol>
</p>
</body>
</html>
8
XP
Displays As…
9
XP
Basic Tags
 Text display:
 <em>, <strong>, <em>
 Structure:
 <h1>, <h2>, <h3>
 <p>
 <ul>, <ol>, <blockquote>
 Attributes:
 Align, text, bgcolor, etc.
10
XP
Basic Tags (2)
 Links:
<a href=“…”>…</a>
 Images:
 <img src=“…”> an empty tag
 Tables
 Use an editor!
 Forms: later
11
XP
More HTML
 Learn on your own
 You may never code in “raw” HTML
 You may need to tweak HTML files created by
a tool
 You will need to understand HTML to code in
JavaScript etc.
 You will need to understand HTML to know
limitations on how docs on the web can be
structured
12
XP
Document Object Model (DOM)
 An model for describing HTML documents
(and XML documents)
 A standard (ok, standards)
 Independent of browser, language
 (ok, mostly)
 A common set of properties/methods to access
everything in a web document
 APIs in JavaScript, for Java, etc.
13
XP
DOM
 You get
anything you
want from…
 More info:
http://en.wikipedia.org/wiki/Document_O
14
bject_Model
XP
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">
document.write('This is my first 
JavaScript Page');
</script>
</body>
</html>
Note the symbol for
line continuation
XP
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">
document.write('<h1>This is my first 
JavaScript Page</h1>');
</script>
</body>
</html>
HTML written
inside JavaScript
XP
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
JavaScript written
An Event
</p>
inside HTML
</body>
</html>
XP
Example Statements
<script language="JavaScript">
window.prompt('Enter
Another event your
name:','');
</script>
<form>
Note quotes: " and '
<input type="button" Value="Press"
onClick="window.alert('Hello');"
>
XP
HTML Forms and JavaScript
 JavaScript is very good at processing
user input in the web browser
 HTML <form> elements receive input
 Forms and form elements have
unique names
 Each unique element can be identified
 Uses JavaScript Document Object Model
(DOM)
XP
Naming Form Elements in HTML
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
XP
Forms and JavaScript
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
XP
Using Form Data
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + 
document.alertform.yourname.value);">
</form>
XP
Tips
 Check your statements are on one
line
 Check your " and ' quotes match
 Take care with capitalisation
 Lay it out neatly - use tabs
 Remember  in the workbook
denotes a continuing line
 Be patient
esentation slides adapted from scom.hud.ac.uk/scomsjw/Web%20Authoring%20Module/Lecture%20Slides/introjs.ppt
XP
W3C Standards






XML, XHTML
CSS, XSL
XSLT
DOM
ECMAScript
etc
24
XP
JavaScript
 An example of a “scripting” langauge that
is embedded in HTML documents
 The browser’s display engine must distinguish
from HTML and Script statements
 Others like this:
 PHP (later in the course)
25
XP
History
 JavaScript created by Netscape
 JScript created by Microsoft
 IE and Netscape renderings are slightly
different
 Standardized by European Computer
Manufacturers Association (ECMA)
 http://www.ecma-international.
org/publications /standards/Ecma-262.htm
26
XP
General Format














<!doctype ...>
<html>
<Head>
<Title> Name of web page </title>
<script type="text/javascript">
...script goes here
</script>
</head
<body>
...page body here: text, forms, tables
...more JavaScript if needed
...onload, onclick, etc. commands here
</body>
</html>
27
XP
Characteristics







Case sensitive
Object oriented
Produces an HTML document
Dynamically typed
Standard operator precedence
Overloaded operators
Reserved words
28
XP
Characteristics






Division with / is not integer division
Modulus (%) is not an integer operator
5 / 2 yields 2.5
5.1 / 2.1 yields 2.4285714285714284
5 % 2 yields 1
5.1 % 2.1 yields 0.8999999999999995
29
XP
Characteristics
 " and ' can be used in pairs
 Scope rules for variables
 Strings are very common data types
 Rich set of methods available
 Arrays have dynamic length
 Array elements have dynamic type
 Arrays are passed by reference
 Array elements are passed by value
30
XP
Motivation for JavaScript
 Netscape, 1995
 Netscape > 90% browser market share
 Opportunity to do “HTML scripting language”
 Brendan Eich
I hacked the JS prototype in ~1 week in May
And it showed! Mistakes were frozen early
- ICFP talk, 2006
Rest of year spent embedding in browser
 Common uses of JavaScript include:




Form validation
Page embellishments and special effects
Dynamic content manipulation
Emerging Web 2.0: client functionality implemented at client
XP
Example 1: simple calculation
<html>
…
<p> … </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>
…
</html>
XP
Example 2: browser events
Mouse event causes
page-defined
function to be called
<script type="text/JavaScript">
function whichButton(event) {
if (event.button==1) {
alert("You clicked the left mouse button!") }
else {
alert("You clicked the right mouse button!")
}}
</script>
…
<body onmousedown="whichButton(event)">
…
</body>
Other events: onLoad, onMouseMove, onKeyPress, onUnLoad
XP
Example 3: page manipulation
 Some possibilities




createElement(elementName)
createTextNode(text)
appendChild(newChild)
removeChild(node)
 Example: Add a new list item:
var list = document.getElementById(‘list1')
var newitem = document.createElement('li')
var newtext = document.createTextNode(text)
list.appendChild(newitem)
newitem.appendChild(newtext)
This example uses the browser Document Object Model (DOM). For now,
we will focus on JavaScript as a language, not its use in the browser.
XP
Design goals
 Brendan Eich’s 2006 ICFP talk
 Make it easy to copy/paste snippets of code
 Tolerate “minor” errors (missing semicolons)
 Simplified onclick, onmousedown, etc., event
handling, inspired by HyperCard
 Pick a few hard-working, powerful primitives
 First class functions for procedural abstraction
 Objects everywhere, prototype-based
 Leave all else out!
XP
Language basics
 JavaScript is case sensitive
 HTML is not case sensitive; onClick, ONCLICK, … are HTML
 Statements terminated by returns or semi-colons (;)
 x = x+1; same as
x = x+1
 Semi-colons can be a good idea, to reduce errors
 “Blocks”
 Group statements using { … }
 Not a separate scope, unlike other languages (see later slide)
 Variables
 Define a variable using the var statement
 Define implicitly by its first use, which must be an
assignment
 Implicit definition has global scope, even if it occurs in nested
scope?
XP
Tutorial Objectives








Understand basic JavaScript syntax
Create an embedded and external script
Work with variables and data
Work with data objects and extract values
from dates
Work with expressions and operators
Create and call a JavaScript function
Work with arrays and conditional statements
Learn about program loops
37
XP
Server-Side Programs
 a user must be connected to the Web
server to run the server-side script
 only the programmer can create or alter
the script
 the system administrator has to be
concerned about users continually
accessing the server and potentially
overloading the system
38
XP
Client-Side Programs
 solve many of the problems associated with
server-side scripts
 can be tested locally without first uploading
it to a Web server
 are likely to be more responsive to the user
 can never completely replace server-side
scripts
39
XP
Introduction to JavaScript
 JavaScript is an interpreted programming or
script language from Netscape.
 JavaScript is used in Web site development to
such things as:
 automatically change a formatted date on a
Web page
 cause a linked-to-page to appear in a popup
window
 cause text or a graphic image to change
during a mouse rollover
40
XP
Java vs. JavaScript
 Requires the JDK to
create the applet
 Requires a Java virtual
machine to run the applet
 Applet files are distinct
from the XHTML code
 Source code is hidden
from the user
 Programs must be saved
as separate files and
compiled before they can
be run
 Programs run on the
server side
 Requires a text editor
 Required a browser that
can interpret JavaScript
code
 JavaScript can be placed
within HTML and XHTML
 Source code is made
accessible to the user
 Programs cannot write
content to the hard disk
 Programs run on the
client side
41
XP
ECMAScript
 The responsibility for the development of a
scripting standard has been transferred to an
international body called the European
Computer Manufacturers Association (ECMA).
 The standard developed by the ECMA is
called ECMAScript, though browsers still refer
to it as JavaScript.
 The latest version is ECMA-262, which is
supported by the major browsers.
42
XP
Other Client-side Languages
 Internet Explorer supports JScript.
 JScript is identical to JavaScript, but there
are some JavaScript commands not
supported in JScript, and vice versa.
 Other client-side programming languages
are also available to Web page designers,
such as the Internet Explorer scripting
language, VBScript.
43
Example of Web Site using
JavaScript
XP
44
XP
Writing a JavaScript Program
 The Web browser runs a JavaScript program
when the Web page is first loaded, or in
response to an event.
 JavaScript programs can either be placed
directly into the HTML file or they can be
saved in external files.
 placing a program in an external file allows
you to hide the program code from the user
 source code placed directly in the HTML file
can be viewed by anyone
45
XP
Writing a JavaScript Program
 A JavaScript program can be placed anywhere
within the HTML file.
 Many programmers favor placing their
programs between <head> tags in order to
separate the programming code from the Web
page content and layout.
 Some programmers prefer placing programs
within the body of the Web page at the
location where the program output is
generated and displayed.
46
XP
Using the <script> Tag
 To embed a client-side script in a Web
page, use the element:
<script type=“text/javascript” >
script commands and comments
</script>
 To access an external script, use:
<script src=“url”
type=“text/javascript”>
script commands and comments
</script>
47
XP
Comments
 The syntax for a single-line comment is:
// comment text
 The syntax of a multi-line comment is:
/*
comment text covering several lines
*/
48
XP
Hiding Script from Older Browsers
 You can hide the script from these browsers
using comment tags:
<script type=“text/javascript”>
<!-- Hide from non-JavaScript browsers
JavaScript commands
// Stop hiding from older browsers -->
</script>
 When a Web browser that doesn’t support
scripts encounters this code, it ignores the
<script> tag.
49
XP
Writing Output to a Web Page
 JavaScript provides two methods to write text
to a Web page:
 document.write(“text”);
 document.writeln(“text”);
 The document.writeln() method differs from
document.write() in that it attaches a carriage
return to the end of each text string sent to the
Web page.
document.write("<h3>News Flash!</h3><br />");
50
XP
JavaScript Syntax Issues
 JavaScript commands and names are casesensitive.
 JavaScript command lines end with a
semicolon to separate it from the next
command line in the program.
 in some situations, the semicolon is
optional
 semicolons are useful to make your code
easier to follow and interpret
51
XP
Working with Variables & Data
 A variable is a named element in a program
that stores information. The following
restrictions apply to variable names:
 the first character must be either a letter or
an underscore character ( _ )
 the remaining characters can be letters,
numbers, or underscore characters
 variable names cannot contain spaces
 Variable names are case-sensitive.
 document.write(Year);
52
XP
Types of Variables
JavaScript supports four different types of
variables:
 numeric variables can be a number, such as
13, 22.5, or -3.14159
 string variables is any group of characters,
such as “Hello” or “Happy Holidays!”
 Boolean variables are variables that accept one
of two values, either true or false
 null variables is a variable that has no value at
all
53
XP
Declaring a Variable
 Before you can use a variable in your
program, you need to declare a variable
using the var command or by assigning the
variable a value.
 Any of the following commands is a
legitimate way of creating a variable named
“Month”:
var Month;
var Month = “December”;
Month = “December”;
54
XP
Working with Dates
 There are two ways to create a date object:
variable = new Date(“month day, year,
hours:minutes: seconds”)
variable = new Date(year, month, day, hours,
minutes, seconds”)
 variable is the name of the variable that
contains the date information
 month, day, year, hours, minutes, and
seconds indicate the date and time
var Today=new Date(“October 15, 2006”);
var Today=new Date(2006, 9, 15);
55
XP
Retrieving the Day & Time Values
 JavaScript stores dates and times as the
number of milliseconds since 6 p.m on
12/31/69.
 Use built in JavaScript date methods to do
calculations.
 If you want the ThisDay variable to store the
day of the month. To get that information,
apply the getDate() method.
DayValue = DateObject.getDate()
56
XP
Retrieving the Month Value
 The getMonth() method extracts the
value of the current month.
 JavaScript starts counting months with 0
for January, you may want to add 1 to the
month number returned by the getMonth()
method.
 ThisMonth = Today.getMonth()+1;
57
XP
Retrieving the Year Value
 The getFullYear() method extracts the
year value from the date variable.
 ThisYear = Today.getFullYear();
58
Working with Expressions
and Operators
XP
 Expressions are JavaScript commands that
assign values to variables.
 Expressions are created using variables,
values, and operators.
 The + operator performs the action of
adding or combining two elements. For
example,
 var ThisMonth = Today.getMonth()+1;
59
XP
Operators
 Binary operators work on two elements in an
expression.
 Unary operators work on only one variable.
 unary operators include: the increment
(++), decrement (--), and negation (-)
operators.
 An increment operator is used to increase the
value of the x variable by one.
x = 100;
y = x++;
61
XP
Operators
 The decrement operator reduces the value
of a variable by 1.
x = 100;
y = x--;
 The negation operator changes the sign of
a variable:
x = -100;
y = -x;
62
XP
Assignment Operators
 Expressions assign values using assignment
operators. “=” is the most common one.
 Additional includes the += operator
 The following create the same results:
x = x + y;
x += y
 Either of the following increase the value of
the x variable by 2:
x = x + 2;
x += 2
63
Assignment Operators
The Math Object & Math
Methods
XP
 Another way of performing a calculation is to
use the JavaScript built-in Math methods.
 These methods are applied to an object called
the Math object.
 The syntax for applying a Math method is:
value = Math.method(variable);
 For example,
AbsValue = Math.abs(NumVar);
65
XP
Creating JavaScript Functions
function function_name(parameters) {
JavaScript commands
}
 parameters are the values sent to the
function (note: not all functions require
parameters)
 { and } are used to mark the beginning and
end of the commands in the function.
67
XP
Creating JavaScript Functions
 Function names are case-sensitive.
 The function name must begin with a letter or
underscore ( _ ) and cannot contain any
spaces.
 There is no limit to the number of function
parameters that a function may contain.
 The parameters must be placed within
parentheses, following the function name, and
the parameters must be separated by
commas.
68
Performing an Action with a
Function
XP
The following function displays a message with
the current date:
function ShowDate(date) {
document.write(“Today is” + date + “<br>”);
}
 there is one line in the function’s command
block, which displays the current date along
with a text string
69
Performing an Action with a
Function
XP
To call the ShowDate function, enter:
var Today = “3/9/2006”;
ShowDate(Today);
 the first command creates a variable named
“Today” and assigns it the text string,
“3/9/2006”
 the second command runs the ShowDate
function, using the value of the Today variable
as a parameter
 result is “Today is 3/9/2006”
70
Returning a Value from a
Function
XP
To use a function to calculate a value use the
return command along with a variable or value.
function Area(Width, Length) {
var Size = Width*Length;
return Size;
}
 the Area function calculates the area of a
rectangular region and places the value in a
variable named “Size”
 the value of the Size variable is returned by
the function
71
Placing a Function
in an HTML File
XP
 The function definition must be placed
before the command that calls the function.
 One convention is to place all of the
function definitions in the <head> section.
 A function is executed only when called by
another JavaScript command.
 It’s common practice for JavaScript
programmers to create libraries of functions
located in external files.
72
document.write("Today is "+ThisMonth+"/"+
ThisDay+"/"+ThisYear+"<br />");
document.write("Only "+DaysLeft+
" days until Christmas");
<head>
<script src="library.js" type="text/javascript">
</script>
</head>
<script type="text/javascript">
var Today=new Date("October 15, 2006");
var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
var DaysLeft=XmasDays(Today);
</script>
document.write("Today is "+ThisMonth+"/"+
ThisDay+"/"+ThisYear+"<br />");
document.write("Only "+DaysLeft+
" days until Christmas");
library.js
function XmasDays(CheckDay) {
var XYear=CheckDay.getFullYear();
var XDay=new Date("December, 25, 2006");
XDay.setFullYear(XYear);
var DayCount=(XDay-CheckDay) /(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
XP
Setting Date Values
JavaScript functions that allow
you to set or change the values of date objects
76
Working with Conditional
Statements
XP
if (condition) {
JavaScript Commands
}
 condition is an expression that is either true
or false
 if the condition is true, the JavaScript
Commands in the command block are
executed
 if the condition is not true, then no action is
taken
77
Comparison, Logical, and
Conditional Operators
XP
To create a condition, you need one of three types
of operators:
 a comparison operator compares the value
of one element with that of another, which
creates a Boolean expression that is either
true or false
 a logical operator connects two or more
Boolean expressions
 a conditional operator tests whether a
specific condition is true and returns one value
if the condition is true and a different value if
the condition is false
78
An Example of
Boolean Expressions
XP
 x < 100;
 if x is less than 100, this expression returns
the value true; however, if x is 100 or
greater, the expression is false
 y == 20;
 the y variable must have an exact value of
20 for the expression to be true
 comparison operator uses a double equal
sign (==)
79
XP
Comparison Operators
80
XP
A Logical Operator
 The logical operator && returns a value of true
only if all of the Boolean expressions are true.
81
XP
A Conditional Operator
tests whether a specific condition is true and
returns one value if the condition is true and a
different value if the condition is false.
 Message = (mail == “Yes”) ? “You have
mail”: “No mail”;
 tests whether the mail variable is equal to the
value “Yes”
 if it is, the Message variable has the value
“You have mail”;
 otherwise, the Message variable has the
value “No mail”.
82
XP
Using an If...Else Statement
if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false
}
 condition is an expression that is either true
or false, and one set of commands is run if
the expression is true, and another is run if
the expression is false
83
if...else Conditional Statement
document.write("Today is " + ThisMonth +
"/“+ThisDay+"/"+ThisYear+"<br />");
if (DaysLeft > 0) {
document.write("Only "+DaysLeft+
" days until Christmas");
} else {
document.write("Happy Holidays from
Nroth Pole Novelties");
}
XP
Using Arrays
 An array is an ordered collection of values
referenced by a single variable name.
 The syntax for creating an array variable is:
var variable = new Array(size);
 variable is the name of the array variable
 size is the number of elements in the array
(optional)
 To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array. The 1st item
has an index value of 0.
85
XP
Using Arrays
To create and populate the array in a single
statement, use:
var variable = new Array(values);
 values are the array elements enclosed in
quotes and separated by commas
 var MonthTxt=new Array(“”, “January”,
“February”, “March”, “April”, “May”, “June”,
“July”, “August”, “September”, “October”,
“November”, “December”);
 January will have an index value of “1”.
86
<script type="text/javascript">
var Today=new Date();
var ThisDay=Today.getDate();
var ThisMonth=Today.getMonth()+1;
var ThisYear=Today.getFullYear();
var DaysLeft=XmasDays(Today);
var MonthTxt = new Array("", "January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October","November", "December");
document.write("Today is "+MonthTxt[ThisMonth]+" " +
ThisDay+", "+ThisYear+"<br />");
if (DaysLeft > 0) {
document.write("Only "+DaysLeft+" days until Christmas");
} else {
document.write("Happy Holidays from North Pole
Novelties");
}
</script>
Creating the MonthText Function in library2.js
function MonthTxt(MonthNumber) {
var Month=new Array();
Month[0]="";
Month[1]="January";
Month[2]="February";
Month[3]="March";
Month[4]="April";
Month[5]="May";
Month[6]="June";
Month[7]="July";
Month[8]="August";
Month[9]="September";
Month[10]="October";
Month[11]="November";
Month[12]="December";
return Month[MonthNumber];
}
Calling the MonthTxt Function
use the ThisMonth variable
to call the MonthTxt function
and then stores the result in
a new variable named “MonthName”
<head>
<script src="library2.js"
type="text/javascript"></script>
</head>
var MonthName=MonthTxt(ThisMonth);
XP
Working with Program Loops
 A program loop is a set of instructions
that is executed repeatedly.
 There are two types of loops:
 loops that repeat a set number of
times before quitting
 loops that repeat as long as a certain
condition is met
90
XP
The For Loop
 The For loop allows you to create a group of
commands to be executed a set number of
times through the use of a counter that tracks
the number of times the command block has
been run.
 Set an initial value for the counter, and each
time the command block is executed, the
counter changes in value.
 When the counter reaches a value above or
below a certain stopping value, the loop ends.
91
XP
The For Loop Continued
for (start; condition; update) {
JavaScript Commands
}
 start is the starting value of the counter
 condition is a Boolean expression that must
be true for the loop to continue
 update specifies how the counter changes in
value each time the command block is
executed
92
Specifying Counter Values in a For Loop
XP
The While Loop
 The While loop runs a command group as
long as a specific condition is met, but it does
not employ any counters.
 The general syntax of the While loop is:
while (condition) {
JavaScript Commands
}
 condition is a Boolean expression that can
be either true or false
96
XP
JavaScript primitive datatypes

Boolean

 Two values: true and false
Number

 64-bit floating point, similar to Java double and Double
 No integer type
 Special values NaN (not a number) and Infinity
String

 Sequence of zero or more Unicode characters
 No separate character type (just strings of length 1)
 Literal strings using ' or " characters (must match)
Special values


null and undefined
typeof(null) = object;
typeof(undefined)=undefined
XP
Objects
 An object is a collection of named properties
 Simple view: hash table or associative array
 Can define by set of name:value pairs
 objBob = {name: “Bob", grade: 'A', level: 3};
 New members can be added at any time
 objBob.fullname = 'Robert';
 Can have methods, can refer to this
 Arrays, functions regarded as objects
 A property of an object may be a function (=method)
 A function defines an object with method called “( )”
function max(x,y) { if (x>y) return x; else return y;};
max.description = “return the maximum of two arguments”;
XP
More about functions
 Declarations can appear in function body
 Local variables, “inner” functions
 Parameter passing
 Basic types passed by value, objects by reference
 Call can supply any number of arguments
 functionname.length : # of arguments in definition
 functionname.arguments.length : # args in call
 “Anonymous” functions (expressions for functions)
 (function (x,y) {return x+y}) (2,3);
 Closures and Curried functions
 function CurAdd(x){ return function(y){return x+y} };
More explanation on next slide
XP
Function Examples

Anonymous functions make great callbacks

setTimeout(function() { alert("done"); }, 10000)
Curried function

function CurriedAdd(x){ return function(y){ return x+y} };
g = CurriedAdd(2);
g(3)
Variable number of arguments
function sumAll() {
var total=0;
for (var i=0; i< sumAll.arguments.length; i++)
total+=sumAll.arguments[i];
return(total); }
sumAll(3,5,3,5,3,2,6)
XP
Use of anonymous functions
 Anonymous functions very useful for callbacks
setTimeout(function() { alert("done"); }, 10000)
// putting alert("done") in function delays evaluation until
call
 Simulate blocks by function definition and call
var u = { a:1, b:2 }
var v = { a:3, b:4 }
(function (x,y) {
var tempA = x.a; var tempB =x.b; //local variables
x.a=y.a; x.b=y.b;
y.a=tempA; y.b=tempB
}) (u,v)
// This works because objects are passed by reference
XP
Basic object features
 Use a function to construct an object
function car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
 Objects have prototypes, can be changed
var c = new car(“Ford”,”Taurus”,1988);
car.prototype.print = function () {
return this.year + “ “ + this.make + “ “ + this.model;}
c.print();
XP
JavaScript functions and this
var x = 5; var y = 5;
function f() {return this.x + y;}
var o1 = {x : 10}
var o2 = {x : 20}
o1.g = f; o2.g = f;
o1.g()
15
o2.g()
25 Both o1.g and o2.g refer to the same function object
Why are the results for o1.g() and o2.g() different ?
XP
More about this

Property of the activation object for fctn call
 In most cases, this points to the object which has the
function as a property (or method).
 Example :
var o = {x : 10, f : function(){return this.x}}
o.f();
10
this is resolved dynamically when the method is executed
Special treatment for nested methods
var o = { x: 10
f : function() {
function g(){ return this.x } ;
return g();
}
};
o.f()
Function g gets the global object as its this property !
XP
XP
Language features
 Stack memory management
 Parameters, local variables in activation records
 Garbage collection
 Automatic reclamation of inaccessible memory
 Closures
 Function together with environment (global variables)
 Exceptions
 Jump to previously declared location, passing values
 Object features
 Dynamic lookup, Encapsulation, Subtyping, Inheritance
 Concurrency
 Do more than one task at a time (JavaScript is single-threaded)
XP
Stack memory management
 Local variables in activation record of function
function f(x) {
var y = 3;
function g(z) { return y+z;};
return g(x);
}
var x= 1; var y =2;
f(x) + y;
XP
Garbage collection
 Automatic reclamation of unused memory
 Navigator 2: per page memory management
 Reclaim memory when browser changes page
 Navigator 3: reference counting
 Each memory region has associated count
 Count modified when pointers are changed
 Reclaim memory when count reaches zero
 Navigator 4: mark-and-sweep, or equivalent
 Garbage collector marks reachable memory
 Sweep and reclaim unreachable memory
Reference http://www.unix.org.ua/orelly/web/jscript/ch11_07.html
Discuss garbage collection in connection with Lisp
XP
Closures

Return a function from function call

function f(x) {
var y = x;
return function (z){y += z; return y;}
}
var h = f(5);
h(3);
Can use this idea to define objects with “private” fields


Description of technique
 http://www.crockford.com/JavaScript/private.html
 http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:W
orking_with_Closures
But there are subtleties (look for __parent__)
XP
Exceptions
 Throw an expression of any type
throw "Error2";
throw 42;
throw {toString: function() { return "I'm an object!"; } };
 Catch
try {
} catch (e if e == “FirstException") {
// do something
} catch (e if e == “SecondException") { // do something else
} catch (e){
// executed if no match above
}
Reference: http://developer.mozilla.org/en/docs/
Core_JavaScript_1.5_Guide :Exception_Handling_Statements
XP
Object features
 Dynamic lookup
 Method depends on run-time value of object
 Encapsulation
 Object contains private data, public operations
 Subtyping
 Object of one type can be used in place of
another
 Inheritance
 Use implementation of one kind of object to
implement another kind of object
XP
Concurrency

JavaScript itself is single-threaded

 How can we tell if a language provides concurrency?
AJAX provides a form of concurrency

Create XMLHttpRequest object, set callback function
Call request method, which continues asynchronously
Reply from remote site executes callback function
 Event waits in event queue…
 Closures important for proper execution of callbacks
Another form of concurrency




use SetTimeout to do cooperative multi-tasking
 Maybe we will explore this in homework …
XP
JavaScript eval




Evaluate string as code
 The eval function evaluates a string of JavaScript code, in scope of
the calling code
Examples
var code = "var a = 1";
eval(code); // a is now '1‘
var obj = new Object();
obj.eval(code); // obj.a is now 1
Most common use
 Efficiently deserialize a large, complicated JavaScript data structures
received over network via XMLHttpRequest
What does it cost to have eval in the language?
 Can you do this in C? What would it take to implement?
XP
Unusual features of JavaScript
 Some built-in functions
 Eval, Run-time type checking functions, …
 Regular expressions
 Useful support of pattern matching
 Add, delete methods of an object dynamically
 Seen examples adding methods. Do you like this? Disadvantages?
 myobj.a = 5; myobj.b = 12; delete myobj.a;
 Redefine native functions and objects (incl undefined)
 Iterate over methods of an object
 for (variable in object) { statements }
 With statement (“considered harmful” – why??)
 with (object) { statements }
XP
References

Brendan Eich, slides from ICFP conference talk

 www.mozilla.org/js/language/ICFP-Keynote.ppt
Tutorial

 http://www.w3schools.com/js/ (still there?)
JavaScript 1.5 Guide

 http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
Douglas Crockford site
 http://www.crockford.com/JavaScript/
 http://20bits.com/2007/03/08/the-philosophy-of-JavaScript/
 W3C school
 www.w3schools.com/Xhtml