35
More about JavaScript More about JavaScript INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

More about JavaScript INE2720 Web Application Software Development Essential Materials

Embed Size (px)

Citation preview

Page 1: More about JavaScript INE2720 Web Application Software Development Essential Materials

More about JavaScriptMore about JavaScript

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

Page 2: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

Outline – Part BOutline – Part B

JavaScript Functions and EventsJavaScript Functions and Events– Events HandlersEvents Handlers

Using Object in JavaScriptUsing Object in JavaScript– Object-Oriented ProgrammingObject-Oriented Programming– JavaScript Object ModelJavaScript Object Model– Using Built-In objects (Predefined Using Built-In objects (Predefined

Object)Object)– Custom Object TypesCustom Object Types

Error in JavaScriptError in JavaScript Exception Handling in JavaScriptException Handling in JavaScript

Page 3: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

FunctionsFunctions

A function is a block of organized A function is a block of organized reusable code (a set of statements) reusable code (a set of statements) for performing a single or related for performing a single or related action.action.

Begins with keyword “function” and Begins with keyword “function” and the function name and “( … )”the function name and “( … )”

Inside the parenthesesInside the parentheses– We can pass parameters to the functionWe can pass parameters to the function– E.g. function myfuc(arg1, arg2) {…}E.g. function myfuc(arg1, arg2) {…}– Built-in and user-defined functionsBuilt-in and user-defined functions

Page 4: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Built-In FunctionsBuilt-In Functions

Functions provided by the language and you Functions provided by the language and you cannot change them to suit your needs.cannot change them to suit your needs.

Some of the built-in functions in JavaScript are Some of the built-in functions in JavaScript are shown here:shown here:– eval - eval(expr)eval - eval(expr)

eval evaluates the expression or statementseval evaluates the expression or statements– isFiniteisFinite

Determines if a number is finiteDetermines if a number is finite– isNaNisNaN

Determines whether a value is “Not a Number”Determines whether a value is “Not a Number”– parseIntparseInt

Converts string literals to integers, no number Converts string literals to integers, no number NaN. NaN.– parseFloatparseFloat

Finds a floating-point value at the beginning of a string.Finds a floating-point value at the beginning of a string.

Page 5: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

User-Defined User-Defined FunctionsFunctions For some functionality, you For some functionality, you

cannot achieve by only using the cannot achieve by only using the built-in functions. built-in functions.

You can define a function as You can define a function as followsfollowsfunction function <function_name> <function_name>

(parameters)(parameters)

{{

// code segments;// code segments;

}}

Page 6: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

Function DeclarationsFunction Declarations

• Declaration SyntaxDeclaration Syntax– Functions are declared using the function reserved Functions are declared using the function reserved

wordword– The return value is not declared, nor are the types of The return value is not declared, nor are the types of

the argumentsthe arguments– Examples:Examples:

functionfunction square square(x)(x) {{ return(x * x);return(x * x); } }

functionfunction factorial factorial(n)(n) {{ if (n <= 0) {if (n <= 0) { return(1);return(1); } else {} else { return(n * factorial(n - 1));return(n * factorial(n - 1)); }}}}

Page 7: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

EventsEvents

Events are the actions that occur Events are the actions that occur as a result of browser activities or as a result of browser activities or user interactions with the web user interactions with the web pages.pages.– Such as the user performs an action Such as the user performs an action

(mouse click or enters data)(mouse click or enters data)– We can validate the data entered by a We can validate the data entered by a

user in a web formuser in a web form– Communicate with Java applets and Communicate with Java applets and

browser plug-insbrowser plug-ins

Page 8: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

Event CategoriesEvent Categories

Keyboard and mouse eventsKeyboard and mouse events– Capturing a mouse event is simpleCapturing a mouse event is simple

Load eventsLoad events– The page first appears on the screen: The page first appears on the screen:

“Loads”, leaves: “Unloads”, …“Loads”, leaves: “Unloads”, … Form-related eventsForm-related events

– onFocus() refers to placing the cursor into onFocus() refers to placing the cursor into the text input in the form.the text input in the form.

OthersOthers– Errors, window resizing.Errors, window resizing.

Page 9: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

Events defined by Events defined by JavaScriptJavaScript

HTML HTML elementselements

HTML HTML tagstags

JavaScript JavaScript defined eventsdefined events

DescriptionDescription

LinkLink <a><a> clickclick

dblClickdblClick

mouseDownmouseDown

mouseUpmouseUp

mouseOvermouseOver

Mouse is clicked on a linkMouse is clicked on a link

Mouse is double-clicked on a linkMouse is double-clicked on a link

Mouse button is pressedMouse button is pressed

Mouse button is releasedMouse button is released

Mouse is moved over a linkMouse is moved over a link

ImageImage <img><img> loadload

abortabort

errorerror

Image is loaded into a browserImage is loaded into a browser

Image loading is abandonedImage loading is abandoned

An error occurs during the image loadingAn error occurs during the image loading

AreaArea <area<area>>

mouseOvermouseOver

mouseOutmouseOut

dblClickdblClick

The mouse is moved over an image map The mouse is moved over an image map areaarea

The mouse is moved from image map to The mouse is moved from image map to outsideoutside

The mouse is double-clicked on an image The mouse is double-clicked on an image mapmap

FormForm <form<form>>

submitsubmit

ResetResetThe user submits a formThe user submits a form

The user refreshes a formThe user refreshes a form

…… …… …… ……

Page 10: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

Event HandlersEvent Handlers

When an event occurs, a code When an event occurs, a code segment is executed in response to segment is executed in response to a specific event is called “event a specific event is called “event handler”.handler”.

Event handler names are quite Event handler names are quite similar to the name of events they similar to the name of events they handle.handle.

E.g the event handler for the “click” E.g the event handler for the “click” event is “onClick”.event is “onClick”.

<HTMLtag<HTMLtag eventhandlereventhandler=“=“JavaScript CodeJavaScript Code””>>

Page 11: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

Event HandlersEvent Handlers

Event HandlersEvent Handlers Triggered whenTriggered when

onChangeonChange The value of the text field, textarea, or a drop The value of the text field, textarea, or a drop down list is modifieddown list is modified

onClickonClick A link, an image or a form element is clicked A link, an image or a form element is clicked onceonce

onDblClickonDblClick The element is double-clickedThe element is double-clicked

onMouseDownonMouseDown The user presses the mouse buttonThe user presses the mouse button

onLoadonLoad A document or an image is loadedA document or an image is loaded

onSubmitonSubmit A user submits a formA user submits a form

onResetonReset The form is resetThe form is reset

onUnLoadonUnLoad The user closes a document or a frameThe user closes a document or a frame

onResizeonResize A form is resized by the userA form is resized by the user

Page 12: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

onClick event HandleronClick event Handler

<html><html>

<head><head>

<title>onClick Event Handler Example</title><title>onClick Event Handler Example</title>

<script <script languagelanguage==““JavaScriptJavaScript””>>

function warnUser(){function warnUser(){ return confirm(“INE2720 students?”); }return confirm(“INE2720 students?”); }

</script></script>

</head></head>

<body><body>

<a href=“reference.html”, <a href=“reference.html”, onClickonClick=“=“return return warnUser();warnUser();”>INE2720 Students access only</a>”>INE2720 Students access only</a>

</body></body>

</html></html>

Page 13: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

onLoad event HandleronLoad event Handler

<html><html>

<head><head>

<title>onLoad and onUnload Event Handler <title>onLoad and onUnload Event Handler Example</title>Example</title>

</head></head>

<body <body onLoadonLoad=“=“alert(‘Welcome User’);alert(‘Welcome User’);” ”

onUnloadonUnload=“=“alert(‘Thanks for visiting the page’);alert(‘Thanks for visiting the page’);”>”>

Load and UnLoad event test.Load and UnLoad event test.

</body></body>

</html></html>

Page 14: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

User Events, Form User Events, Form ExampleExample<html><head><html><head>

<title>Simple JavaScript Button</title><title>Simple JavaScript Button</title>

<script language=“JavaScript"><!--<script language=“JavaScript"><!--

function dontClick() {function dontClick() {

alert("I told you not to click!");alert("I told you not to click!");

}}

// --></script>// --></script>

</head></head>

<body><body>

<h1>Simple JavaScript Button</h1><h1>Simple JavaScript Button</h1>

<form><form>

<input type=“button"<input type=“button"

value="Don't Click Me"value="Don't Click Me"

onClick="dontClick()"onClick="dontClick()">>

</form></form>

</body></html></body></html>

Page 15: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

onMouseOver and onMouseOver and onMouseOut Event onMouseOut Event HandlersHandlers<html><html>

<head><head>

<title>onMouseOver and onMouseOut event <title>onMouseOver and onMouseOut event handler</title>handler</title>

</head></head>

<body><body>

<a href=“link.html” <a href=“link.html”

onMouseOveronMouseOver = = ““status status = = ‘Now mouse is over the link’‘Now mouse is over the link’; ; ““

onMouseOutonMouseOut = = ““statusstatus = = ‘Mouse has moved out’‘Mouse has moved out’;;””>>

A Link PageA Link Page

</a></a>

</body></body>

</html></html>

Page 16: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

Understanding Understanding JavaScript ObjectsJavaScript Objects One of the most important features of JavaScript, One of the most important features of JavaScript,

enables modular programs.enables modular programs. Objects are based on Classes, variables, functions, Objects are based on Classes, variables, functions,

statements are contained in a structure called statements are contained in a structure called class.class.

ClassvarA varB

varC varD

FunctionA (…)

FunctionC (…)

FunctionB (…)

FunctionD (…)

Page 17: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

Class and ObjectClass and Object

You can instantiate an object from a You can instantiate an object from a class by using the constructor function.class by using the constructor function.

JavaScript is said to be an Object-JavaScript is said to be an Object-based programming language.based programming language.

What is What is propertyproperty??– A variable belongs to the object.A variable belongs to the object.

What is What is methodmethod??– It is a function belongs to the object.It is a function belongs to the object.– Function-Valued PropertiesFunction-Valued Properties

Page 18: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

Creating Instances of Creating Instances of ObjectsObjects

You can use the “You can use the “newnew” operator to ” operator to create instances of objects of a create instances of objects of a particular class or object type.particular class or object type.– Variable = new objectType(parameters)Variable = new objectType(parameters)

This objectType() is called constructor.This objectType() is called constructor. E.g. Date is a predefined object type.E.g. Date is a predefined object type.

– Assign the current date and time to objAAssign the current date and time to objA objA = new Date()objA = new Date()

– Assign another date and time to objBAssign another date and time to objB objB = new Date(99,23,5)objB = new Date(99,23,5) 23 May, 99 23 May, 99

Page 19: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

Objects and ClassesObjects and Classes

• Fields Can Be Added On-the-FlyFields Can Be Added On-the-Fly– Adding a new property (field) is a Adding a new property (field) is a

simple matter of assigning a value to simple matter of assigning a value to oneone

– If the field doesn’t already exist when If the field doesn’t already exist when you try to assign to it, JavaScript will you try to assign to it, JavaScript will create it automatically. create it automatically.

– For instance:For instance:

var test = new Object();var test = new Object();test.field1 = "Value 1"; test.field1 = "Value 1"; // Create field1 property// Create field1 propertytest.field2 = 7; test.field2 = 7; // Create field2 property// Create field2 property

Page 20: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

Objects and Classes – Objects and Classes – Literal NotationLiteral Notation• You Can Use Literal NotationYou Can Use Literal Notation

– You can create objects using a shorthand “literal” You can create objects using a shorthand “literal” notation of the formnotation of the form

{ field1:val1, field2:val2, ... , fieldN:valN }{ field1:val1, field2:val2, ... , fieldN:valN }

– For example, the following gives equivalent For example, the following gives equivalent values to values to object1object1 and and object2object2

var object1 = new Object();var object1 = new Object();var object2 = new Object();var object2 = new Object();object1object1..xx = 3; = 3;

object1object1..yy = 4; = 4; object1object1..zz = 5; = 5;

object2object2 = { = { xx:3, :3, yy:4, :4, zz:5 };:5 };

Page 21: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

Objects and Classes - Objects and Classes - ConstructorConstructor• A “Constructor” is Just a Function that Assigns to “this”A “Constructor” is Just a Function that Assigns to “this”

• JavaScript does not have an exact equivalent to Java’s JavaScript does not have an exact equivalent to Java’s class definitionclass definition

• The closest you get is when you define a function that The closest you get is when you define a function that assigns values to properties in the assigns values to properties in the thisthis reference reference

• Calling this function using Calling this function using newnew binds binds thisthis to a new to a new ObjectObject• For example, following is a simple constructor for a For example, following is a simple constructor for a ShipShip

classclass

functionfunction Ship( Ship(xx, , yy, , speedspeed, , directiondirection) {) {

this.x = this.x = xx;;

this.y = this.y = yy;;

this.speed = this.speed = speedspeed;;

this.direction = this.direction = directiondirection;;

}}

Page 22: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

Constructor, ExampleConstructor, Example

var ship1 = new Ship(0, 0, 1, 90);

Page 23: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

Class Methods, Class Methods, ExampleExample Consider a version of the Consider a version of the ShipShip class that includes a class that includes a movemove method method

function degreesToRadians(degrees) {function degreesToRadians(degrees) { return(degrees * Math.PI / 180.0);return(degrees * Math.PI / 180.0); }}

function move() {function move() { var angle = degreesToRadians(this.direction);var angle = degreesToRadians(this.direction); this.x = this.x + this.speed * Math.cos(angle);this.x = this.x + this.speed * Math.cos(angle); this.y = this.y + this.speed * Math.sin(angle);this.y = this.y + this.speed * Math.sin(angle); }}

function Ship(x, y, speed, direction) {function Ship(x, y, speed, direction) { this.x = x;this.x = x; this.y = y;this.y = y; this.speed = speed;this.speed = speed; this.direction = direction;this.direction = direction; this.move = move;this.move = move; }}

Page 24: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Class Methods, ResultClass Methods, Result

var ship1 = new Ship(0, 0, 1, 90);var ship1 = new Ship(0, 0, 1, 90);

ship1.move();ship1.move();

Page 25: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

Objects and Classes - Objects and Classes - ArraysArrays• ArraysArrays

• For the most part, you can use arrays in JavaScript a lot For the most part, you can use arrays in JavaScript a lot like Java arrays. like Java arrays. Here are a few examples:Here are a few examples:

var squares = new Array(5);var squares = new Array(5); for(var i=0; i<squares.length; i++) {for(var i=0; i<squares.length; i++) { vals[i] = i * i;vals[i] = i * i; }} // Or, in one fell swoop:// Or, in one fell swoop: var squares = new Array(0, 1, 4, 9, 16);var squares = new Array(0, 1, 4, 9, 16); var array1 = new Array("fee", "fie", "fo", "fum");var array1 = new Array("fee", "fie", "fo", "fum"); // Literal Array notation for creating an array.// Literal Array notation for creating an array. var array2 = [ "fee", "fie", "fo", "fum" ];var array2 = [ "fee", "fie", "fo", "fum" ];

• Behind the scenes, however, JavaScript simply Behind the scenes, however, JavaScript simply represents arrays as objects with numbered fields represents arrays as objects with numbered fields You can access named fields using either You can access named fields using either object.fieldobject.field

or or object["field"]object["field"], but numbered fields only via , but numbered fields only via object[fieldNumber] object[fieldNumber]

Page 26: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Array, ExampleArray, Example

var arrayObj = new Object();arrayObj[0] = "Index zero";arrayObj[10] = "Index ten";arrayObj.field1 = "Field One";arrayObj["field2"] = "Field Two";

Page 27: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

Build-In JavaScript Build-In JavaScript ObjectsObjects

ObjectObject DescriptionDescription

ArrayArray Creates new array objectsCreates new array objects

BooleanBoolean Creates new Boolean objectsCreates new Boolean objects

DateDate Retrieves and manipulates dates and timesRetrieves and manipulates dates and times

ErrorError Returns run-time error informationReturns run-time error information

FunctionFunction Creates new function objectsCreates new function objects

MathMath Contains methods and properties for performing Contains methods and properties for performing mathematical calculationsmathematical calculations

NumberNumber Contains methods and properties for manipulating Contains methods and properties for manipulating numbers.numbers.

StringString Contains methods and properties for manipulating text Contains methods and properties for manipulating text stringsstrings

Page 28: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

JavaScript ReferencesJavaScript Referenceshttp://developer.netscape.com/docs/manuals/communicator/jsref/contents.htm

Page 29: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

Error and Exception Error and Exception Handling in JavaScriptHandling in JavaScript While executing your code, While executing your code,

runtime exceptions occur.runtime exceptions occur. How can you write error-free How can you write error-free

scripts?scripts?– The onerror event handlerThe onerror event handler– The Error objectThe Error object

http://http://www.irt.org/xref/Error.htmwww.irt.org/xref/Error.htm

– The throw statementThe throw statement– The try … catch … finally blockThe try … catch … finally block

Error and Exception are the same.Error and Exception are the same.

Page 30: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

onerror Event Handleronerror Event Handler

Errors may occur due toErrors may occur due to– syntax errorssyntax errors

Syntax is the rules of grammar and Syntax is the rules of grammar and spellingspelling

– runtime errorsruntime errors The script tries to perform something the The script tries to perform something the

system (browser) cannot do.system (browser) cannot do. To capture error event, JavaScript To capture error event, JavaScript

provides the onerror event handler.provides the onerror event handler. The onerror event handler is The onerror event handler is

associated with the window object.associated with the window object.

Page 31: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

How to use “onerror” How to use “onerror” event handler?event handler?<html><html><head><head><title>onerror event handler example</title><title>onerror event handler example</title><script language=“JavaScript”><script language=“JavaScript”>Function errorHandler(){Function errorHandler(){

alert(“an error has ocurred”);alert(“an error has ocurred”);}}window.onerror = errorHandler;window.onerror = errorHandler;</script></script></head></head><body><body><script language=“JavaScript”><script language=“JavaScript”>

document.write(“Hello there;document.write(“Hello there;</script></script></body></body></html></html>

Page 32: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

Exception Handling in Exception Handling in JavaScriptJavaScript An exception is an error generated by the script.An exception is an error generated by the script. The code that handles an exception is called an The code that handles an exception is called an

exception handler that will catch exceptions.exception handler that will catch exceptions.

Normal script flow of control

If an error is occurred,An exception will be thrown.

The exception is caughtand handled by anexception handler

Page 33: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

try … catch … finallytry … catch … finally

trytry{{

// normal statements // normal statements // might result in an error, throw exceptions// might result in an error, throw exceptions

}}catch(errorVariable)catch(errorVariable){{

// statements that execute in the exception event// statements that execute in the exception event}}finallyfinally{{

// After the execution in the catch or try block,// After the execution in the catch or try block,// the statements in the finally block are // the statements in the finally block are executed.executed.

}}

Page 34: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

Try … catch … finally Try … catch … finally exampleexample

<script language=“JavaScript”><script language=“JavaScript”>try{try{

document.write(“Try block begins” + “<br>”);document.write(“Try block begins” + “<br>”);// create a syntax error// create a syntax erroreval (“10 + * 5”);eval (“10 + * 5”);

}}catch(errVar){catch(errVar){document.write(“Exception caught” + “<br>”);document.write(“Exception caught” + “<br>”);document.write(“Error name: “ + errVar.name + “<br>”);document.write(“Error name: “ + errVar.name + “<br>”);document.write(“Error message: “ + errVar.message + document.write(“Error message: “ + errVar.message + “<br>”);“<br>”);

}}finally{finally{document.write(“Finally block reached!”);document.write(“Finally block reached!”);

}}</script></script>

Page 35: More about JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

ReferencesReferences

Deitel: Chapter 7, 8, 9, 11Deitel: Chapter 7, 8, 9, 11 CWP: Chapter 24CWP: Chapter 24

The End.The End. Thank you for patience!Thank you for patience!