74
1 Representation and Management of Data on the Web Javascript Javascript

1 Representation and Management of Data on the Web Javascript

Embed Size (px)

Citation preview

Page 1: 1 Representation and Management of Data on the Web Javascript

1

Representation and

Management of Data on the

Web

JavascriptJavascript

Page 2: 1 Representation and Management of Data on the Web Javascript

2

OverviewOverview

• A "scripting" language for HTML pages

• Embed code in HTML pages so they are downloaded directly to browser

• The browser interprets and executes the script (it is not compiled)

• Do not declare data types for variables (loose typing)

• Dynamic binding – object references checked at runtime

Page 3: 1 Representation and Management of Data on the Web Javascript

3

Overview (cont.)Overview (cont.)

• Scripts can manipulate "browser

objects:"

– HTML form elements

– Images

– Frames

– etc.

• For security – cannot write to disk (when

run on a client)

Page 4: 1 Representation and Management of Data on the Web Javascript

4

AbilitiesAbilities

• Generating HTML content dynamically

• Monitoring and responding to user events

• Validate forms before submission

• Manipulate HTTP cookies

• Interact with the frames and windows of the browser

• Customize pages to suit users

Page 5: 1 Representation and Management of Data on the Web Javascript

5

It is It is notnot Java Java

• Java :

– compilation required (not a script)

– can create “stand alone” application

– object-oriented

• Why is it called Javascript then?

Page 6: 1 Representation and Management of Data on the Web Javascript

Web browser

HTML Page:

<SCRIPT>

…code..…

</SCRIPT>

Desktop access

InternetHTML/HTTP

TCP/IP

HTML/HTTP

TCP/IP

Web

(HTTP)

Server

HTML

pages w/

embedded

script

Remote host

built-in

JavaScript

interpreter

Web Architecture for Web Architecture for JavaScriptJavaScript

"CLIENT" "SERVER"

Page 7: 1 Representation and Management of Data on the Web Javascript

7

ExampleExample

<HTML>

<HEAD><TITLE>An Hello World Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

document.write("<font size='+4'>");

document.writeln("Hello World!<br>");

document.writeln("What a boring example</font>")

</SCRIPT>

</HEAD>

<BODY> <!-- An empty document body --> </BODY>

</HTML>

Why do we need <br> if we used writeln?

RESULT

Page 8: 1 Representation and Management of Data on the Web Javascript

8

ExampleExample

<HTML>

<HEAD><TITLE>An Hello World Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

document.write("<font size='+4'>");

document.writeln("Hello World!<br>");

document.writeln("What a boring example</font>")

</SCRIPT>

</HEAD>

<BODY> <h1>My Hello World Example</h1> </BODY>

</HTML>

RESULT

Page 9: 1 Representation and Management of Data on the Web Javascript

9

Past and PresentPast and Present

• Built into Netscape Navigator since v2.0 (early 1996)

• Developed independently of Java

• Proprietary, but submitted as standard and built into Microsoft IE 3.0 and later

• Standardized by ECMA (European Computer Manufacture’s Association) into ECMAscript

• EMCAscript joins JavaScript and Jscript to one standard

Page 10: 1 Representation and Management of Data on the Web Javascript

10

Client and ServerClient and Server

• JavaScript can be used

– On the client side

– On the server

• More lightweight and reliable on clients

than Java (Applets)

• Useful for developing interactive

interface (Dynamic HTML)

Page 11: 1 Representation and Management of Data on the Web Javascript

11

CGI and other Server-side CGI and other Server-side ArchitecturesArchitectures

• Strengths– allows access to

server files and databases

– makes no assumptions about client computer capabilities, puts little burden on it

– easier to manage and control on server

– more secure for client

• Weaknesses

– puts most of processing

load on server

– requires round-trip for

every submission, using

valuable bandwidth

– cannot provide

instantaneous response

expected with GUI

– less secure for server

Page 12: 1 Representation and Management of Data on the Web Javascript

12

JavaScript Reserved JavaScript Reserved KeywordsKeywords

• break

• case

• continue

• delete

• do

• else

• false

• for

• function

• if

• in

• new

• null

• return

• switch

• this

• true

• typeof

• var

• void

• while

• with

Page 13: 1 Representation and Management of Data on the Web Javascript

13

Non Used Reserved WordsNon Used Reserved Words

• catch

• class

• const

• debugger

• default

• enum

• export

• extends

• finally

• import

• super

• try

Page 14: 1 Representation and Management of Data on the Web Javascript

14

Javascript VariablesJavascript Variables

• Untyped!

• Can be declared with var keyword:

var foo;

• Can be created automatically by

assigning a value:

val = 1;

val = “Thank for all the fish";

val has changed from an int to a String!

Page 15: 1 Representation and Management of Data on the Web Javascript

15

Variables NamesVariables Names

• A variable name can be any valid identifier

• The identifier is a series of characters – Consisting of letters (lower and upper case),

digits, and underscores (_)

– Does not begin with a digit

– Does not contain any space

• Javascript is case sensitive (foo and FOO are different)

Page 16: 1 Representation and Management of Data on the Web Javascript

16

VariablesVariables

• Local variable is available only in the

function where it is declared

• Global variable is available all over the

document

• A variable declaration

– Inside a function creates a local variable

– Outside a function creates a global variable

• Local variables must be declared with var

Page 17: 1 Representation and Management of Data on the Web Javascript

17

LiteralsLiterals

• The typical bunch:

– Numbers 17 123.45

– Strings “Let it be”

– Boolean: true false

– Arrays: [1,“ab ba”,17.234]

– null

– undefinedArrays can hold anything!

You can use typeof(A) to get the type of A:

number, string, object..

Page 18: 1 Representation and Management of Data on the Web Javascript

18

OperatorsOperators

• Arithmetic, comparison, assignment, bit

wise, Boolean (pretty much just like Java)

+ - * / % ++ --

== != > < >= <=

&& || ! & | << >>

+= -= *= /= %=

Page 19: 1 Representation and Management of Data on the Web Javascript

19

The Special Plus CommandThe Special Plus Command

• Which of the following two is correct?

• What is the ‘type’ of the answer?

x = “The answer is” + 42y = 42 + “is the answer”

Page 20: 1 Representation and Management of Data on the Web Javascript

20

Which is correct?Which is correct?

• Which of the following two is correct?

• What is the ‘type’ of the answer?

x = "37" + 7y = "37" - 7

Page 21: 1 Representation and Management of Data on the Web Javascript

21

Types of EqualityTypes of Equality

• The equals == checks if both operands

are equal after performing type

conversion

• The equals === checks if both operands

are of the same type and equal

• Example:

– 3 == "3" (true or false?)

– 3 === "3" (true or false?)

Page 22: 1 Representation and Management of Data on the Web Javascript

22

Types of InequalityTypes of Inequality

• The equals != checks if both operands are

unequal after performing type conversion

• The equals !== checks if both operands

are not of the same type and or not equal

• Example:

– 3 != "3" (true or false?)

– 3 !== "3" (true or false?)

Page 23: 1 Representation and Management of Data on the Web Javascript

Conditional OperatorsConditional Operators

• equals

if (a == b) {…}

• not equals

if (a != b) {…}

• greater than or equal to

if (a >= b) {...}

• less than or equal to

if (a <= b) {...}

Page 24: 1 Representation and Management of Data on the Web Javascript

Boolean OperatorsBoolean Operators

• and

if (true && true) {…}

• or

if (true || false) {…}

• not

if (! false) {...}

Page 25: 1 Representation and Management of Data on the Web Javascript

25

<HTML>

<HEAD><TITLE>Using Variables</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

var firstNumber = 11,

secondNumber = 23,

sum;

sum = firstNumber + secondNumber;

document.write("<FONT COLOR = 'blue' SIZE = '6'>The sum of " + firstNumber + " and " + secondNumber + " is </FONT>");

document.write(" <FONT COLOR = ‘red' SIZE = '7'>" + sum + "</FONT>");

</SCRIPT>

</HEAD>

<BODY> <!-- An empty document body --> </BODY>

</HTML>

RESULT

Page 26: 1 Representation and Management of Data on the Web Javascript

26

Control StructuresControl Structures

• Some just like Java:

if if-else ?: switch

for while do-while

• And a few not like in Java

for (var in object)

with (object)

Page 27: 1 Representation and Management of Data on the Web Javascript

JavaScript’s Basic JavaScript’s Basic ConstructsConstructs

• sequence (block)

• condition (selection)

• loop (iteration)

Page 28: 1 Representation and Management of Data on the Web Javascript

JavaScript ConstructsJavaScript Constructs

• sequence (block)

– executes with no conditions

– semicolons optional using one statement per line, but not a bad thing to use all the time

var metushelahAge = 130; var yourAverageAge

yourAverageAge = metushelahAge - 98

var myObject = new Object("initial value")

more statements here..

…..

Page 29: 1 Representation and Management of Data on the Web Javascript

JavaScript ConstructsJavaScript Constructs

• condition (selection)

if (condition) {statements if true}

else {statements if false}

if (metushelahAge < yourAverageAge) {

document.write ("<body><h2>its true that

Metushelah is younger than most of you,")

document.write ("<br>computers never lie!</h2>

</body>")

}

Page 30: 1 Representation and Management of Data on the Web Javascript

JavaScript ConstructsJavaScript Constructs

• loop (iteration): both for and while loops

are available

for (var i=0; i < inputAge.length; i++) {

var oneChar = inputAge.substring (i, i+1)

if (oneChar < "0" || oneChar > "9") {

alert("Please enter a valid number “

+ oneChar + " is not valid.")

}

}

Page 31: 1 Representation and Management of Data on the Web Javascript

31

<HTML>

<HEAD><TITLE>Loops Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

for (var counter = 1 ; counter <= 8 ; ++counter) {

document.write(“<P><FONT COLOR = ‘blue’ SIZE = ‘ “ + counter + “ '> Now with font size " + counter + " </FONT></P> “);

}

</SCRIPT>

</HEAD>

<BODY> <!-- An empty document body --> </BODY>

</HTML>

RESULT

Page 32: 1 Representation and Management of Data on the Web Javascript

32

JavaScript FunctionsJavaScript Functions

• Functions are first class citizens

• The keyword function used to define a

function (subroutine):

function add(x,y) {

return(x+y);

}

Page 33: 1 Representation and Management of Data on the Web Javascript

33

Function Input and OutoutFunction Input and Outout

• Numbers and Boolean values always

passed to functions using call-by-value

• For objects, a call-by-reference is used

to pass them to the functions

• Numbers and Boolean values are

always returned by value

• Objects returned by reference

Page 34: 1 Representation and Management of Data on the Web Javascript

34

ExampleExample

• Computing the Fibonacci numbers.

HTML Page

Page 35: 1 Representation and Management of Data on the Web Javascript

35

<HTML>

<HEAD><TITLE>Functions Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

function fibonacciValue() {

var value = parseInt(document.fibonacciForm.number.value );

window.status = "Calculating Fibonacci number for " + value;

document.fibonacciForm.result.value = fibonacci(value);

window.status = "Done Calculating Fibonacci number";

}

function fibonacci( n ) {

if (n == 0 || n == 1) return n;

else return fibonacci( n - 1 ) + fibonacci( n - 2 );

}

</SCRIPT></HEAD>

Page 36: 1 Representation and Management of Data on the Web Javascript

36

<BODY>

<FORM NAME = "fibonacciForm">

<TABLE BORDER = "1" BGCOLOR = "blue">

<TR><TD BGCOLOR = "cyan">Enter a number</TD>

<TD><INPUT NAME = "number" TYPE = "text"></TD>

<TD><INPUT TYPE = "button" VALUE = "Calculate"

ONCLICK = "fibonacciValue()"</TR>

<TR><TD BGCOLOR = "cyan">Fibonacci Value</TD>

<TD><INPUT NAME = "result" TYPE = "text"> </TD> </TR>

</TABLE>

</FORM>

</BODY>

</HTML>

Page 37: 1 Representation and Management of Data on the Web Javascript

37

Function ArgumentsFunction Arguments

• Within a function, its arguments can be

accessed with arguments[i].

• The number of arguments is

arguments.length

• A function can be created that takes

any number of arguments

Page 38: 1 Representation and Management of Data on the Web Javascript

38

ExampleExample

function myConcat(separator) {   result="" // initialize list   // iterate through arguments   for (var i=1; i<arguments.length; i++) {      result += arguments[i] + separator   }   return result}

//What does this return?

myConcat(", ","red","orange","blue")

Page 39: 1 Representation and Management of Data on the Web Javascript

39

Global Functions (1)Global Functions (1)

• escape – changes characters in a string

that are not in the ASCII characters set to

HEX

• unescape – decodes the escape encoding

• eval – gets a string of JavaScript code,

evaluates it and executes it

– It allows dynamic code execution

Page 40: 1 Representation and Management of Data on the Web Javascript

40

Global Functions (2)Global Functions (2)

• isNaN – takes a numeric argument and

returns true if the value is not a number

• parseFloat – takes a string argument and

converts its beginning to a float number (or

return NaN)

• parseInt – takes a string argument and

converts its beginning to an integer number

(or return NaN)

Page 41: 1 Representation and Management of Data on the Web Javascript

41

Global Functions (3)Global Functions (3)

• isFinite – given a numeric argument it

returns true if the argument is not

– NaN

– Number.POSITIVE_INFINITY

– Number.NEGATIVE_INFINITY

Page 42: 1 Representation and Management of Data on the Web Javascript

42

ObjectsObjects

• Objects have attributes and methods

• There are pre-defined objects and

user-defined object types

• Using objects has similarity to the

syntax of C++/Java:

objectName.attributeNameobjectName.methodName()

Page 43: 1 Representation and Management of Data on the Web Javascript

43

Objects Are Like ArraysObjects Are Like Arrays

myCar.make = "Ford"myCar.model = "Mustang"myCar.year = 66;

myCar[“make”] = "Ford"myCar[“model”] = "Mustang"myCar[“year”] = 66;

Page 44: 1 Representation and Management of Data on the Web Javascript

44

function show_props(obj, obj_name) { var result = "" for (var i in obj) result += obj_name + "." + i + " = " + obj[i] + "\n" return result}

myCar.make = FordmyCar.model = MustangmyCar.year = 66

So, the function call show_props(myCar, "myCar")would return the following:

Page 45: 1 Representation and Management of Data on the Web Javascript

45

Creating a New ObjectCreating a New Object

• There are two ways to create new

objects:

• Object Initializer:

– objectName={prop1:val1, …, propN:valN}

• Constructor Function:

– define a constructor function

– create the new object using new

Page 46: 1 Representation and Management of Data on the Web Javascript

46

ExampleExample

function car(make, model, year) { this.make = make this.model = model this.year = year}

theMazda = new car(“Mazda", “323", 1991)theHonda = {make:”Honda”, year:1992, color:"red",wheels:4,

engine:{cylinders:4,size:2.2}}

Page 47: 1 Representation and Management of Data on the Web Javascript

47

Creating a MethodCreating a Method

• A method of an object is a function

that has been assigned to the object:

object.methodName = functionName

Page 48: 1 Representation and Management of Data on the Web Javascript

48

ExampleExample

function displayCar() { var result = "A Beautiful " + this.year + " " + this.make + " " + this.model; document.writeln(result)}

function car(make, model, year) { this.make = make this.model = model this.year = year this.displayCar = displayCar}

Setting the method

Page 49: 1 Representation and Management of Data on the Web Javascript

49

Eval ExampleEval Example

function Dog(name,breed,color) { this.name=name this.breed=breed this.color=color}

myDog = new Dog("Gabby")myDog.breed="Lab"

var breed='Shepherd'

document.write("<P>" + eval('breed'))document.write("<BR>" + myDog.eval('breed'))

Page 50: 1 Representation and Management of Data on the Web Javascript

50

Eval ExampleEval Example

function stone(str) { eval("this."+str) this.y=43 this["z"] = 44}

flint = new stone("x=42")

document.write("<BR>flint.x is " + flint.x)document.write("<BR>flint.y is " + flint.y)document.write("<BR>flint.z is " + flint.z)

Page 51: 1 Representation and Management of Data on the Web Javascript

51

Deleting an ObjectDeleting an Object

• To delete an object just set the object

reference to null

• When are objects that are not set to

null being removed?

Page 52: 1 Representation and Management of Data on the Web Javascript

52

Array ObjectsArray Objects

• Arrays are supported as objects

• Attribute length

• Methods include:

concat, join, pop, push, reverse,

sort

Joins elements into a string

Joins two arrays

Page 53: 1 Representation and Management of Data on the Web Javascript

53

Creating a New ArrayCreating a New Array

• var a = [“red”, “blue”, “green”]

– Allocates an array of 3 cells and initializes the values

• var b = new Array(5)

– Allocates an array of 5 cells without initializing values

• var c = new Array()

– Creates a new empty array

Page 54: 1 Representation and Management of Data on the Web Javascript

54

Array Example CodeArray Example Code

var a = [8,7,6,5];

for (i=0;i<a.length;i++)a[i] += 2;

b = a.reverse();

Page 55: 1 Representation and Management of Data on the Web Javascript

55

Understanding ArraysUnderstanding Arrays

• Array literals:

– arr1 = ["hello", 1, 33]

• Accessing arrays: (what is the result of)

– document.writeln(arr1.length)

– document.writeln(arr1[0])

– document.writeln(arr1["abc"])

– arr1[10]=66

– document.writeln(arr1.length)

Page 56: 1 Representation and Management of Data on the Web Javascript

56

Passing Arrays to Passing Arrays to FunctionsFunctions

• Arrays can be passed to functions as

arguments

• The array is passed by call-by-

reference

• The name of the array is given to the

function

Page 57: 1 Representation and Management of Data on the Web Javascript

57

<HTML><HEAD><TITLE>Arrays Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

function start() {

var colors = ["red", "blue", "green"]

printArray(colors);

printArray(colors);

}

function printArray( arr) {

for (var i in arr) {

document.writeln("<FONT SIZE=5 COLOR=" + arr[i] + ">"

+ arr[i] + " </FONT><BR>");

arr[i] = "gray";

}

} </SCRIPT>

</HEAD><BODY ONLOAD = "start()"> </BODY></HTML>

RESULT

Page 58: 1 Representation and Management of Data on the Web Javascript

58

Multidimentional ArraysMultidimentional Arrays

• var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0,

0]];

• var myArray = [[1, 2, 3], [1], [1, 2]];

• Going over the array

for (var i in myArray ) {

for (var j in myArray[i])

document.write(myArray[i][j]);

Page 59: 1 Representation and Management of Data on the Web Javascript

59

Other Object TypesOther Object Types

• String: manipulation methods

• Math: trig, log, random numbers

• Date: date conversions

• RegExp: regular expressions

• Number: limits, conversion to string

Page 60: 1 Representation and Management of Data on the Web Javascript

60

Math Common MethodsMath Common Methods

• abs(x)

• round(x)

• ceil(x)

• floor(x)

• max(x, y)

• min(x, y)

• cos(x)

• sin(x)

• tan(x)

• exp(x)

• pow(x, y)

• sqrt(x)

• log(x)Math Also includes constants

such as: Math.E, Math.PI

Page 61: 1 Representation and Management of Data on the Web Javascript

61

String Common MethodsString Common Methods

• charAt (index)

• charCodeAt(index)

• concat(string)

• fromCharCode(value1,

value2, …)

• indexOf(substring,

index)

• lastIndexOf(substring,

index)

• slice(start, end)

• split(string)

• substr(start, length)

• substring(start, end)

• toLowerCase()

• toUpperCase()

• toString()

• valueOf()

Page 62: 1 Representation and Management of Data on the Web Javascript

62

Methods that Generate HTMLMethods that Generate HTML

• anchor(name) – wraps the source with

– <A name = name></A>

• big() – wraps the source with

– <BIG></BIG>

• blink() – wraps with

– <BLINK></BLINK>

• bold() – wraps the source with

– <B></B>

• fixed() – wraps the source with

– <TT></TT>

Page 63: 1 Representation and Management of Data on the Web Javascript

63

More Methods that Generate More Methods that Generate HTMLHTML

• fontcolor(color) – wraps with

– <FONT color=“color”></FONT>

• fontsize(size) – wraps with

– <FONT size=“size”></FONT>

• italic() – wraps with

– <I></I>

• link(url)

– <A href = url></A>

Page 64: 1 Representation and Management of Data on the Web Javascript

64

More Methods that Generate More Methods that Generate HTMLHTML

• small() – wraps the source with

– <SMALL></SMALL>

• strike() – wraps the source with

– <STRIKE></STRIKE>

• sub() – wraps the source with

– <SUB></SUB>

• sup() – wraps the source with

– <SUP></SUP>

Page 65: 1 Representation and Management of Data on the Web Javascript

65

Date Common MethodsDate Common Methods

• getDate(), getFullYear(), getMonth(),

getDay

• getTime(), getHours(), getMinutes(),

getSeconds(), getMilliseconds()

Page 66: 1 Representation and Management of Data on the Web Javascript

66

<HTML>

<HEAD><TITLE>Time Example</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

function getTimes() {

var current = new Date();

var out = "Day: " + current.getDay()+"\n";

out = out.concat("Month: " + current.getMonth() + "\n");

out = out.concat("Year: " + current.getFullYear() + "\n");

out = out.concat("GMT Time: " + current.toUTCString() + "\n");

out = out.concat("Time: " + current.toString() + "\n");

timesForm.output.value = out;

}

</SCRIPT>

</HEAD>

Page 67: 1 Representation and Management of Data on the Web Javascript

67

<BODY>

<FORM NAME="timesForm">

<P>

<INPUT NAME = "getTimeButton" TYPE = "button" VALUE = "Get Time" ONCLICK = "getTimes()">

<P>

<TEXTAREA NAME = "output" ROWS ="10" COLS="42">

</TEXTAREA>

</FORM>

</BODY>

</HTML>

RESULT

Page 68: 1 Representation and Management of Data on the Web Javascript

68

Predefined ObjectsPredefined Objects

• In JavaScript the following objects are

automatically created for you (always

available)

– document

– navigator

– screen

– window

Page 69: 1 Representation and Management of Data on the Web Javascript

69

The The documentdocument Object Object

• Many attributes of the current

document are available via the

document object:

Title Referrer

URL Images

Forms Links

Colors

Page 70: 1 Representation and Management of Data on the Web Javascript

70

Objects HierarchyObjects Hierarchy

• JavaScript objects include object hierarchy + (property or method)– window.document.lastModified

– metushelahBirthday.getYear()

• need not be fully qualified– document.lastModified

• proceeds from most to least general– window.document.forms[0].inputText1.value

• all names are case sensitive

Page 71: 1 Representation and Management of Data on the Web Javascript

71

Objects Objects Object Oriented Object Oriented

• Objects – complex data types or “containers” that have both data and code

• Methods – code or “functions” that work on an object’s properties

• Properties – data that are stored and retrieved via object references

• This is not true "OO" because the object hierarchy is not extensible, you can create new objects, but cannot extend existing ones

Page 72: 1 Representation and Management of Data on the Web Javascript

72

The The withwith Statement Statement

• Establishes the default object for a set

of statements

• Within the set of statements, any

property references that do not specify

an object are assumed to be for the

default object

Page 73: 1 Representation and Management of Data on the Web Javascript

73

Example of Example of withwith

var a, x, y

var r=10

with (Math) {

   a = PI * r * r

   x = r * cos(PI)

   y = r * sin(PI/2)

}

Page 74: 1 Representation and Management of Data on the Web Javascript

74

Dynamic HTMLDynamic HTML

HTML

CSSJava Script

HTML HTML

Dynamic HTML

HTML

CSS

Java Script