76
1 Introduction to Web Application Introduction to Java Script

1 Introduction to Web Application Introduction to Java Script

Embed Size (px)

Citation preview

Page 1: 1 Introduction to Web Application Introduction to Java Script

1

Introduction to Web Application

Introduction to Java Script

Page 2: 1 Introduction to Web Application Introduction to Java Script

2

Topics• Review CSS

• Overview Java Script

• A simple Java Script in Web Page

• Syntax of Java Script

Page 3: 1 Introduction to Web Application Introduction to Java Script

3

Review CSS

• What is CSS?

• Box model

• text flow

• id and class

• inline, embedded, and outsource CSS

• Develop CSS in Dreamweaver

• How to use CSS?

Page 4: 1 Introduction to Web Application Introduction to Java Script

4

Overview of Java Script

Page 5: 1 Introduction to Web Application Introduction to Java Script

5

Introduction to JavaScript

• JavaScript scripting language– Enhances functionality and appearance

– Client-side scripting• Makes pages more dynamic and interactive

– Foundation for complex server-side scripting

Page 6: 1 Introduction to Web Application Introduction to Java Script

6

History of JavaScript

• Originally developed by Netscape, as LiveScript

• Became a joint venture of Netscape and Sun in 1995, renamed JavaScript

• Now standardized by the European Computer Manufacturers Association as ECMA-262 (also ISO 16262)

• Microsoft’s JScript

Page 7: 1 Introduction to Web Application Introduction to Java Script

7

JavaScript vs. Java

• JavaScript and Java are only related through syntax– JavaScript is dynamically typed– JavaScript’s support for objects is very different

Page 8: 1 Introduction to Web Application Introduction to Java Script

8

JavaScript and Object Orientation

• JavaScript is NOT an object-oriented programming language– Does not support class-based inheritance– Cannot support polymorphism– Has prototype-based inheritance, which is much

different

Page 9: 1 Introduction to Web Application Introduction to Java Script

9

JavaScript and Object Orientation

• JavaScript Objects:– JavaScript objects have collections of

properties, which are like the members of classes in Java and C++

• Properties can be data properties or method properties

– All JavaScript objects are accessed through references

Page 10: 1 Introduction to Web Application Introduction to Java Script

10

Write a Simple Java Script in Web Page

Page 11: 1 Introduction to Web Application Introduction to Java Script

11

Ways to Add JavaScript to HTML

• Inline Style<html> <head> <title>A First Program in JavaScript</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" ); // --> </script> </head><body></body></html>

Page 12: 1 Introduction to Web Application Introduction to Java Script

12

Page 13: 1 Introduction to Web Application Introduction to Java Script

13

Ways to Add JavaScript to HTML

• Written in the <head> of a document• <script> tag

– Indicate that the text is part of a script– type attribute

• Specifies the type of file and the scripting language use

– writeln method• Write a line in the document

Page 14: 1 Introduction to Web Application Introduction to Java Script

14

Ways to Add JavaScript to HTML

• Scripts are often hidden from browsers that do not include JavaScript interpreters by putting them in special comments <!--

-- JavaScript script –

//-->

Page 15: 1 Introduction to Web Application Introduction to Java Script

15

Ways to Add JavaScript to HTML• Indirectly, as a file specified in the src attribute of

<script>, as in <script type=“text/javascript” language = "JavaScript" src = "myScript.js"> … </script>

<html><head><title>Use External Script</title><script type="text/javascript"

language="Javascript" src="scripts/alert.js"/>

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

Page 16: 1 Introduction to Web Application Introduction to Java Script

16

Other Example of Java Script<html> <head> <title>Printing a Line with Multiple Statements</title> <script type = "text/javascript"> <!-- document.write( "<h1 style = \"color: magenta\">" ); document.write( "Welcome to JavaScript " + "Programming!</h1>" ); // --> </script> </head><body></body></html>

\” “\n new line\t horizontal table\r Carriage return\\ \\’ ‘

\” “\n new line\t horizontal table\r Carriage return\\ \\’ ‘

Page 17: 1 Introduction to Web Application Introduction to Java Script

17

Page 18: 1 Introduction to Web Application Introduction to Java Script

18

Other Example of Java Script

<html > <head><title>Printing Multiple Lines</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Welcome to<br />

JavaScript" + "<br />Programming!</h1>" ); // --> </script> </head><body></body></html>

Page 19: 1 Introduction to Web Application Introduction to Java Script

19

Page 20: 1 Introduction to Web Application Introduction to Java Script

20

Other Example of Java Script<html> <head><title>Printing Multiple Lines in a Dialog Box</title> <script type = "text/javascript"> <!-- window.alert( "Welcome to \n

JavaScript\n Programming!" );

// --> </script> </head> <body><p>Click Refresh (or Reload) to run this script again.</p>

</body></html>

Page 21: 1 Introduction to Web Application Introduction to Java Script

21

Page 22: 1 Introduction to Web Application Introduction to Java Script

22

Other Example of Java Script<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using Prompt and Alert Boxes</title>

<script type = "text/javascript"> <!-- var name; // string entered by the user name = window.prompt( "Please enter your name",

"GalAnt" ); document.writeln( "<h1>Hello " + name + ", welcome to JavaScript programming!</h1>" ); // --> </script> </head> <body><p>Click Refresh (or Reload) to run this script again.</p> </body></html>

Different with JavaDifferent with Java

Page 23: 1 Introduction to Web Application Introduction to Java Script

23

Page 24: 1 Introduction to Web Application Introduction to Java Script

24

Other Example of Java Script<script type = "text/javascript"> <!-- var name; // string entered by the user

now = new Date(); hour = now.getHours(); name = window.prompt( "Please

enter your name", "GalAnt" );

if ( hour < 12 ) document.write( "<h1>Good Morning, " ); // determine whether the time is PM …

document.writeln( name + ", welcome to JavaScript programming!</h1>" ); // --> </script>

Page 25: 1 Introduction to Web Application Introduction to Java Script

25

Page 26: 1 Introduction to Web Application Introduction to Java Script

26

Summary of Example

• Write some simple tag in Page

• Alert

• Prompt

• Difference between Java and Java Script

Page 27: 1 Introduction to Web Application Introduction to Java Script

27

Syntax of Java Script

• Identifiers and reserved words

• Comments

• Data types, literals and variables

• Operators and expressions

• Control statements

• Functions and screen output

• Object creation and modification

• Array

Page 28: 1 Introduction to Web Application Introduction to Java Script

28

Identifiers and reserved words

• Identifier form: – Begin with a letter or underscore, followed

by any number of letters, underscores, and digits.

– No length limitation– Case sensitive– Can not be reserved words

• Example– _a, a, a1

Page 29: 1 Introduction to Web Application Introduction to Java Script

29

Identifiers and reserved words

• In JavaScript, identifiers are used to: – name variables, – name functions, – provide labels for loops.

• 25 reserved words, plus future reserved words

Page 30: 1 Introduction to Web Application Introduction to Java Script

30

Comments

• Two forms of comments: – // Rest of a line is considered a comment – /* … */ All lines in it are comments

• JavaScript statements usually do not need to be terminated by semicolons, but we’ll do it

Page 31: 1 Introduction to Web Application Introduction to Java Script

31

Data Types

• In JavaScript, there are three primary data types (String, Number, Boolean) one composite data type (Object), and two special data types (Null, Undefined).

Page 32: 1 Introduction to Web Application Introduction to Java Script

32

Data Types

• Number, String, and Boolean have wrapper objects (Number, String, and Boolean), the wrapper objects provide properties and methods for primitive values

• All objects are allocated on the heap; all primitive values are allocated elsewhere

Page 33: 1 Introduction to Web Application Introduction to Java Script

33

Data Types

Page 34: 1 Introduction to Web Application Introduction to Java Script

34

Data Types

• String Data Type:– A string value is a chain of zero or more

Unicode characters (letters, digits, and punctuation marks) strung together.

• Number Data Type:– In JavaScript, there is no distinction between

integer and floating-point values; a JavaScript number can be either (internally, JavaScript represent all numbers as floating-point values).

Page 35: 1 Introduction to Web Application Introduction to Java Script

35

Data Types

• Boolean Data Type:– Whereas the string and number data types can

have a virtually unlimited number of different values, the Boolean data type can only have two. They are the literals “true” and “false”

• Null Data Type:– The null data type has only one value in

JavaScript: null. – The null keyword cannot be used as the name of

a function or variable.

Page 36: 1 Introduction to Web Application Introduction to Java Script

36

Data Types

• Null Data Type:– You can erase the contents of a variable (without

deleting the variable) by assigning it the null value

• Undefined Data Type:– The undefined value is returned when you use:

• an object property that does not exist, • a variable that has been declared, but has never had a

value assigned to it.

Page 37: 1 Introduction to Web Application Introduction to Java Script

37

Literals

• Numeric literals – Just like Java– All numeric values are stored in double-

precision floating point

• String literals– Delimited by either ' or “– Can include escape sequences (e.g., \t)– All String literals are primitive values

Page 38: 1 Introduction to Web Application Introduction to Java Script

38

Literals

• Boolean values are true and false

• The only Null value is null

• The only Undefined value is undefined

Page 39: 1 Introduction to Web Application Introduction to Java Script

39

Variables

• The first time a variable appears in your script is its declaration

• Variables can be either implicitly or explicitly declared, and explicit declarations are recommended. You do this using the var keyword.

• A variable that has been declared but not assigned a value has the value undefined

Page 40: 1 Introduction to Web Application Introduction to Java Script

40

Operators

Page 41: 1 Introduction to Web Application Introduction to Java Script

41

String Properties and Methods

• String catenation operator: +– Operands can be variables or string literals

• String properties & methods:– length e.g., var len = str1.length; (a property)– charAt(position) e.g., str.charAt(3)– indexOf(string) e.g., str.indexOf('B')– substring(from, to) e.g., str.substring(1, 3)– toLowerCase() e.g., str.toLowerCase()

Page 42: 1 Introduction to Web Application Introduction to Java Script

42

String Properties and Methods• Conversion Functions

– parseInt(string) and parseFloat(string)• The string must begin with a digit or sign and

have a legal number; otherwise NaN is returned

• Not often needed, because of coercions

– toString()

Page 43: 1 Introduction to Web Application Introduction to Java Script

43

Control Statements

• Similar to C, Java, and C++

• Compound statements are delimited by braces, but compound statements are not blocks (cannot declare local variables)

Page 44: 1 Introduction to Web Application Introduction to Java Script

44

Control Statements

• Selection Statements:– If…else– Switch– ? :

Page 45: 1 Introduction to Web Application Introduction to Java Script

45

Control Statements• Loop Statements:

– for– for…in…– while– do…while

<script type="text/javascript" language="Javascript">

var myArray = new Array("itemA","itemB","itemC");

for( key in myArray )

{

document.writeln("<br />");

document.writeln(myArray[key]);

}

</script>

Page 46: 1 Introduction to Web Application Introduction to Java Script

46

Control Statements

• Others:– break– continue– return

Page 47: 1 Introduction to Web Application Introduction to Java Script

47

Functions

• We place all function definitions in the head of the HTML document, and all calls in the body

function function_name([formal_parameters]) {

-- body –

}

Page 48: 1 Introduction to Web Application Introduction to Java Script

48

Functions

• Variables explicitly declared in a function are local

• If a variable appears in a script that is defined both as a local variable and as a global variable, the local variable has precedence.

Page 49: 1 Introduction to Web Application Introduction to Java Script

49

Functions

• Actual parameter vs. formal parameter

• Parameters are passed by value, but when a reference variable is passed, the semantics are pass-by-reference

• There is no clean way to send a primitive by reference

Page 50: 1 Introduction to Web Application Introduction to Java Script

50

Functions

• All parameters are sent through a property array, arguments, which has the length property

• There is no type checking of parameters, nor is the number of parameters checked (excess actual parameters are ignored, excess formal parameters are set to undefined)

Page 51: 1 Introduction to Web Application Introduction to Java Script

51

Functions

• Return value is the parameter of return– If there is no return, or if the end of the function

is reached, undefined is returned– If return has no parameter, undefined is

returned

Page 52: 1 Introduction to Web Application Introduction to Java Script

52

Functions

• Functions are objects, so variables that reference them can be treated as other object references (can be passed as parameters, assigned to variables, and be elements of an array)– If fun is the name of a function:

ref_fun = fun; /* Now ref_fun is a reference to fun */ref_fun(); /* A call to fun */

Page 53: 1 Introduction to Web Application Introduction to Java Script

53

Function

• Recursivefunction factorial(number){

if (number <= 1) //base case

return 1;

else

return number*factorial(number-1);

}

Page 54: 1 Introduction to Web Application Introduction to Java Script

54

Screen Output

• The JavaScript model for the HTML document is the Document object

• The model for the browser display window is the Window object

• The Window object has two properties, document and window, which refer to the Document and Window objects, respectively

Page 55: 1 Introduction to Web Application Introduction to Java Script

55

Screen Output

• The document object has methods write and writeln which dynamically create contents

Page 56: 1 Introduction to Web Application Introduction to Java Script

56

Screen Output

• The Window object has three methods for creating dialog boxes, alert, confirm, and prompt– The default object is the current window, so the

object need not be included in the call to any of these three

Page 57: 1 Introduction to Web Application Introduction to Java Script

57

Objects in JavaScript

• JavaScript objects are collections of properties and methods.– A property is a value or set of values (in the

form of an array or object) that is a member of an object

– A method is a function that is a member of an object

Page 58: 1 Introduction to Web Application Introduction to Java Script

58

Objects in JavaScript

• JavaScript supports two kinds of objects – Intrinsic (or "built-in") objects, includes Array,

Boolean, Date, Math, etc.– User-define objects

Page 59: 1 Introduction to Web Application Introduction to Java Script

59

Object Creation

• Objects can be created with a new expression– The most basic object is one that uses the

Object constructor, as in var myObject = new Object();

• The new object has no properties - a blank object

Page 60: 1 Introduction to Web Application Introduction to Java Script

60

Constructors

• JavaScript constructors are special methods that create and initialize the properties for newly created objects

• When the constructor is called, this is a reference to the newly created object

Page 61: 1 Introduction to Web Application Introduction to Java Script

61

<html><head><title>JavaScript object</title><script type="text/javascript" language="Javascript"><!--

function pasta(grain, width, shape, hasEgg){

this.grain = grain;this.width = width; this.shape = shape; this.hasEgg = hasEgg;

}var myobj = new pasta("wheat", 0.3, "oval", true);

//--></script></head><body>

<h1>This is H1 element</h1><p>Let's see the effective of javascript</p>

<script type="text/javascript" language="Javascript">

document.writeln("<h1>" + myobj.grain + "</h1>");

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

Page 62: 1 Introduction to Web Application Introduction to Java Script

62

Constructors

function plane(newMake, newModel, newYear){

this.make = newMake;

this.model = newModel;

this.year = newYear;

}

myPlane = new plane("Cessna",

"Centurnian",

"1970");

Page 63: 1 Introduction to Web Application Introduction to Java Script

63

Constructors

• Can also have method properties:function displayPlane() {

document.write("Make: ", this.make, "<br />");

document.write("Model: ", this.model, "<br />");

document.write("Year: ", this.year, "<br />");

}

Now add the following to the constructor:this.display = displayPlane;

Page 64: 1 Introduction to Web Application Introduction to Java Script

64

Object Modification

• Properties can be added to any object, any time:var myAirplane = new Object();myAirplane.make = "Cessna "; myAirplane.model = "Centurian";

• The number of properties in a JavaScript object is dynamic

• Objects can be nested, so a property could be itself another object, created with new

Page 65: 1 Introduction to Web Application Introduction to Java Script

65

Object Modification

• Properties can be accessed in two ways:– by dot notation

var property1 = myAirplane.model;– in array notation

var property1 = myAirplane["model"];

• If you try to access a property that does not exist, you get undefined

Page 66: 1 Introduction to Web Application Introduction to Java Script

66

Object Modification

• Properties can be deleted with delete, as in delete myAirplane.model;

• Another Loop Statement– for (identifier in object) statement or compound

for (var prop in myAirplane) document.write(myAirplane[prop] +

"<br />");

Page 67: 1 Introduction to Web Application Introduction to Java Script

67

Arrays

• Arrays in JavaScript are objects with some special functionality

• Array elements can be primitive values or references to other objects

• All array elements are allocated dynamically from the heap, JavaScript arrays have dynamic length

Page 68: 1 Introduction to Web Application Introduction to Java Script

68

Arrays

• Array objects can be created in two ways: with new, or by assigning an array literal, which is a list of values enclosed in brackets:– var myList = new Array(24); – var myList2 = new Array(24, "bread", true);– var myList3 = [24, "bread", true];

Page 69: 1 Introduction to Web Application Introduction to Java Script

69

Arrays• Length of array:

– The array length is dynamic and the length property stores the length

– The lowest index of every JavaScript array is zero

– The length of an array is the highest subscript to which an element has been assigned, plus 1

• myList[122] = "bitsy"; // length is 123

Page 70: 1 Introduction to Web Application Introduction to Java Script

70

Arrays• Length of array:

– Because the length property is writeable, you can set it to make the array any length you like, as in

• myList.length = 150;

– This can also shorten the array (if the new length is less than the old length)

– Only assigned elements take space

Page 71: 1 Introduction to Web Application Introduction to Java Script

71

Sort in Array p355

• A.sort (compareIntegers)

• function compareIntegers(value1, value2)

• {return parseInt(value1)-parseInt(value2)<=0;

• }

Page 72: 1 Introduction to Web Application Introduction to Java Script

72

Multidimensional Arrays

• Two-dimensional arrays analogous to tables– Rows and columns

• Specify row first, then column

– Two subscripts

Page 73: 1 Introduction to Web Application Introduction to Java Script

73

Multidimensional Arrays

a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 0

Row 1

Row 2

Column 0 Column 1 Column 2 Column 3

Row subscript (or index)

Array name

Column subscript (or index)

a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Fig. 11.12 Two-dimensional array with three rows and four columns.

Page 74: 1 Introduction to Web Application Introduction to Java Script

74

Multidimensional Arrays

• Declaring and initializing multidimensional arrays– Group by row in square brackets– Treated as arrays of arrays– Creating array b with one row of two elements

and a second row of three elements:

var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

Page 75: 1 Introduction to Web Application Introduction to Java Script

75

Multidimensional Arrays

• Also possible to use new operator– Create array b with two rows, first with five

columns and second with three:

var b;

b = new Array( 2 ); b[ 0 ] = new Array( 5 );b[ 1 ] = new Array( 3 );

Page 76: 1 Introduction to Web Application Introduction to Java Script

76

Summary

• Java Script Examples

• Java Script Syntax

• Preview Chapter 13, 14, 15, 16