Fundamentals of Web Programming a

Fundamentals of Web a Programming JavaScript: Object Model and JavaScript Core Teodor Rus [email protected] The University of Iowa, Department of Comp...
Author: Mercy Jackson
1 downloads 2 Views 163KB Size
Fundamentals of Web a Programming JavaScript: Object Model and JavaScript Core Teodor Rus [email protected]

The University of Iowa, Department of Computer Science a

Copyright 2009 Teodor Rus. These slides have been developed by Teodor Rus using material published by R.W.Sebesta, Programming the World Wide Web , Addison

Wesley 2009. They are copyrighted materials and may not be used in other course settings outside of the University of Iowa in their current form or modified form without the express written permission of the copyright holder. During this course, students are prohibited from selling notes to or being paid for taking notes by any person or commercial firm without the express written permission of the copyright holder.

Introduction System Software. Copyright Teodor Rus – p.1/59

Content • Overview of JavaScript; • Object Orientation and JavaScript; • General Syntactic Characteristics; • Primitives, Operations, and Expressions; • Screen Output and Keyboard Input;

Introduction System Software. Copyright Teodor Rus – p.2/59

Scripting Languages JavaScript is a scripting language. This means that JavaScript expressions are scripts not programs! What is the difference? • A script is interpreted by a program (interpreter). A program is executed by the computer processor; • A script cannot have access to computer resources (CPU, I/O, Memory). A program is a user of computer resources; • One can compile scripts and run them as programs. If this is the situation, the language nature changes.

Introduction System Software. Copyright Teodor Rus – p.3/59

Origins • Was developed in early 1990 by Brendan Erich of Netscape under the name Mocha and later LiveScript; (In 1995 became a joint venture of Netscape and Sun Microsystems (currently Oracle) under the name JavaScript);

• In late 1990 a language standard for JavaScript was developed by European Computer Manufacturers Association as ECMA-262, approved by ISO as ISO-16262; • The ECMA-262 is now in version 3 which corresponds to Netscape’s version 1.5 of JavaScript; Current standard specification can be found at: http://www.ecma-international.org/publications/standard/Ecma-262.htm

Note: Microsoft JavaScript is called JScript; official name of the standard language is ECMAScript.

Introduction System Software. Copyright Teodor Rus – p.4/59

Structure JavaScript can be divided in three parts: 1. The core: i.e., the hart of the language including operators, expressions, statements, and subprograms (functions); 2. Client-side: the collection of JavaScript Objects that support the control of a browser and interactions with the user; 3. Server-side: the collection of JavaScript Objects that make the language useful on a Web server, such as supporting communication with a database; Note: since PHP is mainly used for server programming we look here only to Client-side JavaScript, which is an XHTML-embedded scripting language.

Introduction System Software. Copyright Teodor Rus – p.5/59

JavaScript and Java JavaScript and Java are actually very different: • Although JavaScript is said to be an OO language its object model is quite different from that of Java or C++; • Java is a strongly typed language; JavaScript is dynamically typed, making compile time type checking impossible; • Objects in Java are static; JavaScript objects are dynamic, (the number of members of data and methods of a JavaScript object can change during execution);

• The main similarity between Java and JavaScript is the syntax of their expressions, assignment statements, and control statements.

Introduction System Software. Copyright Teodor Rus – p.6/59

Client-side JavaScript • Client-side JavaScript scripts are embedded in XHTML documents and are interpreted by the browser; • Client-side JavaScript cannot replace all server-side computing: JavaScript supports no file operations, database access, and networking (this is done by server); • JavaScript can be used as alternative to Java applets, with the advantage of being easier to learn and use: since JavaScript scripts are an integral part of the XHTML document, no secondary downloading is necessary; • However, Java applets are far more capable of producing graphics in browser displays.

Introduction System Software. Copyright Teodor Rus – p.7/59

Event Drive System An EDS is a model of behavior where computations occur as reactions to the events that happens in the environment of the system. Examples:

• Intelligent systems are event driven (human behavior in the environment, a computer operating system, a business, the Web itself); • An EDS detects events that happens in the environment and reacts to them (in an intelligent manner); • An EDS must be able to (1) generate and detects events, (2) react to events, (3) interact with event producers in the environment; JavaScript allows Web programmer to (1) generate events, (2) detect events, (3) react to events.

Introduction System Software. Copyright Teodor Rus – p.8/59

Web as Event Driven System Button clicks and mouse movements are detected and are used to trigger computations. • Even without forms, user interactions are possible using tags attributes, and are simple to program, making possible to generate new content in the browser display dynamically; • Document Object Model (DOM) allows JavaScript scripts to access and modify CSS properties and content of any element of a display XHTML document making documents highly dynamic; • Much of what JavaScript scripts typically do is event driven. Thus, JavaScript supports event driven programming which is actually required outside of the Web programming.

Introduction System Software. Copyright Teodor Rus – p.9/59

XHTML Document Processing Normal document processing: The browser reads the lines of the document and renders its window according to the tags, attributes, and content it finds. 1. When a script is encountered in the document, the browser uses JavaScript interpreter to “interpret" the script; 2. When the end of the script is reached the browser goes back to reading the XHTML document and displaying its content.

Introduction System Software. Copyright Teodor Rus – p.10/59

Embedding JavaScript 1. Explicit embedding: JavaScript code physically resides in the XHTML document; makes document difficult to read; person who creates and maintain XHTML may be distinct from the person who creates the script. Disadvantage:

2. Implicit embedding: develop JavaScript using its own files and include in the XHTML document script’s path. hide script from the browser user, support portability among browsers. Advantage:

Introduction System Software. Copyright Teodor Rus – p.11/59

Facts 1. Explicit embedded scripts can appear anywhere in the XHTML document; 2. Scripts that produce content upon request (I.e., functions associated with form buttons) are placed in document’s head; 3. Scripts that are interpreted just once are placed in document body.

Introduction System Software. Copyright Teodor Rus – p.12/59

Object-Oriented Language A language is object-oriented if it supports: 1. An encapsulation mechanism with information hiding for defining abstract data types (classes); 2. Class instantiation into objects with virtual methods (methods that can be overridden within an inheriting class) (Objects); 3. Inheritance (Hierarchical construction).

Introduction System Software. Copyright Teodor Rus – p.13/59

Object Orientation and JavaScript JavaScript is an object-based language: • JavaScript does not have classes; • JavaScript objects are predefined. A JavaSscipt object serves both as object and as class. That is, a JavaSscript object is a model. • JavaScript cannot have class-based inheritance (has no classes), although it support a technique (called prototype-based inheritance) that can be used to simulate aspects of inheritance; • JavaScript cannot support polymorphisms.

Introduction System Software. Copyright Teodor Rus – p.14/59

Observation Despite the fact that JavaScript is not an OO language: • Much of JavaScript design is rooted in concepts and approaches used in OO programming; • Client-side JavaScript deal with documents and document elements which are modeled with objects!

Introduction System Software. Copyright Teodor Rus – p.15/59

JavaScript Objects JavaScript Objects: • Are collections of properties which correspond to classes in Java; • Each property is either a data or a function (method) property; • Data properties appear in two categories: 1. primitive values, and 2. references to objects; Note: variables that refer to objects are called objects instead of references.

Introduction System Software. Copyright Teodor Rus – p.16/59

Accessing JavaScript Objects JavaScript uses non-object types for some of the simplest data types, called primitives. • Primitives can often be implemented in hardware, and are like scalar variables in C; • All objects in a JavaScript program are indirectly accessed through variables, which are like references in Java. • All primitive values in a JavaScript program are accessed directly like scalars in C and Java. These are called value types.

Introduction System Software. Copyright Teodor Rus – p.17/59

More about Objects • Properties of an object are referenced by attaching the name of the property to the variable that references the objects. Example:

if myCar is a variable that references the car object, then

myCar.engine references the engine property.

• The root object in JavaScript is Object. (Object is the ancestor of all objects through prototype inheritance)

• Object has some methods but no data properties. All other objects are specializations of Object. (all inherit Object’s methods, though they are overridden). • A JavaScript object appears as a list of property/value pairs; properties are names and values are data values or functions.

• All functions are objects and are referenced through variables.

Introduction System Software. Copyright Teodor Rus – p.18/59

Facts 1. The collection of properties of a JavaScript object is dynamic (properties can be added or deleted at any time). 2. Every object is characterized by its collection of properties, although objects do not have types in any formal sense.

Introduction System Software. Copyright Teodor Rus – p.19/59

Syntactic Characteristics JavaScripts can appear in XHTML documents as content of a < script > tag where: • The attribute type must be set to "text/javascript"; • The attribute src must be set to the script file name (that ends in .js), as seen below:

Note: < script > element requires < /script > closing tag even though it has no contents.

Introduction System Software. Copyright Teodor Rus – p.20/59

Observation There are situations where a small amount of JavaScript code is embedded in an XHTML document as the contents of the < script > tag as follows: document.write("Hello from JavaScript!");

Note: some documents may have a large number of places where JavaScript code is embedded. This makes it cumbersome to place all JavaScript code in a separate file.

Introduction System Software. Copyright Teodor Rus – p.21/59

JavaScript Identifiers Are similar to those of other PL: 1. must begin with a letter, an underscore (_), or a dollar ($) sign; 2. subsequent characters may be letters, underscores, dollar signs, or digits.

Note: There is no length limit for identifiers and they are case sensitive; among others, identifiers are used as variable names. Note: by convention programmer-defined variable names do not include upper case letters. Identifier usage:

Introduction System Software. Copyright Teodor Rus – p.22/59

JavaScript Reserved Words Table 1:

JavaScript Reserved Words

break

delete

function

return

typeof

case

do

if

switch

var

catch

else

in

this

void

continue

finally

instanceof

throw

while

default

for

new

try

with

Other reserved words for future use in JavaScript can be found at the ECMA Web site. Note: alert, open, java, self are predefined.

Introduction System Software. Copyright Teodor Rus – p.23/59

Comments 1. Two slashes (//): the rest of the line is comment; 2. Lines between /* and */ (as in C) are comments.

Introduction System Software. Copyright Teodor Rus – p.24/59

Embedding Issues • Some browser may recognize < script > tag but have no JavaScript interpreters. They ignore the content of the script; • There are browsers in use that do not recognize < script > tag; such browsers display the script element as if it were just texts. (To avoid this problem enclose script elements in XHTML comment); • XHTML validator: an embedded script that includes recognizable tags, such as < br/ >, in the output of the script, causes validator to report errors. • When scripts are in XHTML comments, the end of comment (–>) must be JavaScript commented, (that is, // –>, see helloJS.html) • When the end of line coincides with what could be the end of a statement, the interpreter inserts (;) Hence, put each script statement on its own line terminated by (;).

Introduction System Software. Copyright Teodor Rus – p.25/59

Primitive Types 1. Number: 2. String: 3. Boolean: 4. Undefined: 5. Null: Note: JavaScript includes predefined objects named Number, String, Boolean, called wrapper objects. Number and String types can be treated as they were objects.

Introduction System Software. Copyright Teodor Rus – p.26/59

Primitives and Objects Figure 1 shows the difference between primitives and objects. Nonheap memory

...

Prim Obj

primitive 17 ...

r

...

Figure 1:

Heap memory '

$

Object 17

& -

%

Primitives and Objects

Introduction System Software. Copyright Teodor Rus – p.27/59

Literals • All numeric literals are values of type Number, represented in double-precision floating-point. Literal numbers in a script can have the form of integer or FP values. • FP literals can have decimal points or exponents or both; • Integer literals are sequence of digits; if octal their first digit is 0x or 0X. • String literals: are sequences of characters delimited by single (’) or double (") quotes. They can include escape sequences (\n, \t); single quote must be preceded by backslash, double quote must be preceded by double backslash

• Boolean values: true and false are result of Boolean expression evaluation.

Introduction System Software. Copyright Teodor Rus – p.28/59

Other Primitives Types • The only value of type Null is the word null (no value); • The only value of type Undefined is word undefined (the value of an undefined variable).

Introduction System Software. Copyright Teodor Rus – p.29/59

Variables Variable are identifiers: • Variables can be declared using the reserved word var: var counter, index, pi = 3.14159265, stop_flag = true;

or they can be simple used by assigning values; • Variables are dynamically typed (i.e., a variable can be used for anything); Type of the value a particular variable has is determined by the context. Recommendation:

all variables should be declared using var.

Introduction System Software. Copyright Teodor Rus – p.30/59

Numeric Operations • Binary: +, -, *, /, % • Unary: plus (+), negate (-), decrement (- -), increment (++) (used as in C); • Precedence rules: Operator

Associativity

++, - -, unary -, unary +

right

*, /, %

left

binary +, binary -

left

Introduction System Software. Copyright Teodor Rus – p.31/59

JavaScript Objects • Math object; • Number object; • Boolean object; • String object; • Date object; • Screen object; • Document object; • Window object;

Introduction System Software. Copyright Teodor Rus – p.32/59

The Math Object The Math Object: provides a collection of properties of numbers and methods that operate on Number objects. • The Math object has methods for trigonometric functions; Example:

sin for sine, cos for cosine, etc.

• Other methods are floor (to truncate), round (to round), max, etc. • All Math methods are referenced through the Math object, as in Math.sin(x).

Introduction System Software. Copyright Teodor Rus – p.33/59

Number Object The Number Object: includes a collection of properties that have constant values as listed below: Property

Meaning

MAX_VALUE

Largest representable number

MIN_VALUE

Smallest representable number

NaN

Not a number

POSITIVE_INFINITY

Represent + infinity

NEGATIVE_INFINITY

Represent - infinity

PI

The value of π

Introduction System Software. Copyright Teodor Rus – p.34/59

Facts 1. Number object has a method toString (inherited from Object) that convert a number to a string; 2. Any arithmetic operation that results in error return NaN (Not a Number); 3. Use isNAN() to determine whether an entity is NaN. Example: if var a = NaN; then isNaN(a) returns true.

Introduction System Software. Copyright Teodor Rus – p.35/59

Boolean Object Boolean Object should not be confused with primitive values true and false. • The Boolean object has a method toString that converts its argument to true or false; • If a Boolean object is used as a conditional expression, it evaluates to true, unless its value is null or undefined.

Introduction System Software. Copyright Teodor Rus – p.36/59

String Object The String Object: • Strings are unit scalar values (not arrays of char); • String Object include a large collection of methods (see table below) and one property, length; Method

Parameters

Result

charAt

a number (n)

character in the String object at position n

indexOf

a character (r)

position of r in string

substring

n1, n2: numbers

substring (n1,n2)

toLowerCase

none

convert string to lower case

toUpperCase

none

convert string to uppercase

Introduction System Software. Copyright Teodor Rus – p.37/59

Facts 1. String catenation is +. Example: "Freddie"+"Freeloader" = "FreddieFreeloader" 2. JavaScript coerce string values to and from String objects. Hence, difference between string value and string object has no effect on scripts; 3. String methods can be used on string values as they were string objects; 4. Characters in a string are numbered starting with 0 (zero).

Introduction System Software. Copyright Teodor Rus – p.38/59

Example var str = "George"; str.charAt(2) is ’o’ str.indexOf(’r’) is 3 str.substring(2,4) is ’org’ str.toLowerCase() is ’george’

Introduction System Software. Copyright Teodor Rus – p.39/59

Date Object The Date Object: is created with the constructor Date: Example: var today = new Date(); Properties of Date object are:

• local and are Coordinated Universal Time, (UTC, named Greenwich Mean Time); • Methods of Date object are in the table Methods of Date Object.

Introduction System Software. Copyright Teodor Rus – p.40/59

Methods of Date Object Table 2: Methods of Date Object Method

Returns

toLocaleString

A string of Date information

getDate

The day of the month

getDay

The day of the week, number in (0,6)

getFullYear

The year

getHours

Number of the hour in (0,24)

getTime

Number of milliseconds from 1 Jan. 1970

getMinutes

Number of minutes in (0,59)

getSeconds

Number of seconds in (0,59)

getMilliseconds

Number of milliseconds in (0,999)

Introduction System Software. Copyright Teodor Rus – p.41/59

Screen Output A JavaScript script is interpreted when the browser finds it or finds a reference to a script file in the body of the XHTML document. Hence:

• The normal output screen for JavaScript is the same as the screen in which the host XHTML document is displayed; • JavaScript models the XHTML document with the Document Object (to be seen further); • The window in which browser displays the object is modeled with the Window Object which includes two properties: document, which refers to the Document Object, and window, which is self referential.

Introduction System Software. Copyright Teodor Rus – p.42/59

Document Object Has several properties and methods: • write() method: creates script output, which is a dynamically created XHTML document content; Example:

to output "The result is: 42" where 42 is the value of variable result use:

document.write("The result is: ", result, "
");

Note: since write() creates XHTML code the only useful punctuation is provided by XHTML tags. • The writeln() method adds "\n" to its parameter. Note: write() can take any number of parameters, which are concatenated and placed in the output.

Introduction System Software. Copyright Teodor Rus – p.43/59

Window Object Window object includes three methods that create dialog boxes for three specific kinds of user interaction. • The default object for JavaScript is the Window Object currently being displayed; • Consequently, call to the three Window methods need not include an object reference.

Introduction System Software. Copyright Teodor Rus – p.44/59

Window Object Methods 1. alert(): opens a dialog window and displays its parameter in that window, together with an OK button. Parameter string is XHTML code, therefore it may include \n but never < br/ >. Example call:

alert("The sum is:" + sum + "\ n");

2. confirm(): opens a dialog window in which displays its argument along with two buttons: OK and Cancel. confirm() returns a boolean: true for OK and false for Cancel; Example use:

var question = confirm("Do you want to continue?");

3. prompt(): creates a dialog window (as confirm()) that contains a textbox, used to collect input from user, which prompt() returns as its value. prompt() takes two arguments: a string that prompts the user for input, and a default feedback. Example use:

name = prompt("What is your name?", "");

Introduction System Software. Copyright Teodor Rus – p.45/59

Facts 1. alert(), prompt(), confirm() cause the browser to wait for a user response; 2. In case of alert() OK button must be pressed; prompt() and confirm() wait for either OK or Cancel.

Introduction System Software. Copyright Teodor Rus – p.46/59

Examples 1. File confirm.html illustrates the use of alert(), confirm(), and prompt(); 2. The file roots2.html illustrates JavaScript features where: • JavaScript gets the coefficients of a quadratic equation from the user using prompt(); • Computes and displays the real roots; • If the roots are not real, NaN is displayed.

Introduction System Software. Copyright Teodor Rus – p.47/59

roots.html Quadratic Equation Solver

Introduction System Software. Copyright Teodor Rus – p.48/59

roots.js // roots.js // Solves a quadratic equation //Get the coefficients var a = prompt("What is the value of var b = prompt("What is the value of var c = prompt("What is the value of // Compute the roots var rootPart = Math.sqrt(b * b - 4.0 var denom = 2.0 * a; // Compute and display the roots var root1 = (-b + rootPart) / denom; var root2 = (-b - rootPart) / denom; document.write("Root 1 is: ", root1, document.write("Root 2 is: ", root2,

’a’?\n", ""); ’b’?\n", ""); ’c’?\n", ""); * a * c);

"
"); "
");

Introduction System Software. Copyright Teodor Rus – p.49/59

The typeof Operator typeof

returns the type of its operands.

• If the operand is of primitive type Number, String, Boolean it produces "number", "string", "boolean", respectively; • If the operand is null or an object, typeof produces "object"; (this shows that JavaScript objects have no type); • If the operand is a variable that has not been assigned a value, typeof produces "undefined"; Note: typeof always produces a string; its operand is placed after the operator in or not in parentheses (i.e., typeof

x and typeof(x) are

equivalent).

Introduction System Software. Copyright Teodor Rus – p.50/59

Type Conversions •

Implicit;



Explicit.

Introduction System Software. Copyright Teodor Rus – p.51/59

Implicit Type Conversions Are called coercions and are performed by the interpreter as required by context. Examples:

1. "August " + 2009 coerces 2009 to a string producing "August 2009"; 2. 7 * "3" (* is used only with numbers) so result is 21; 3. null is converted to 0, undefined is NaN.

Introduction System Software. Copyright Teodor Rus – p.52/59

Explicit Type Conversions Are primarily between strings and numbers: • Using constructor String: var strValue = String(value); converts value to string; • Using constructor Number: var number = Number(aString); converts aString to number; • Using method toString(): var num = 6; var strValue = num.toString(); var strValueBinary = num.toString(2); // use base as argument

• By string catenation or numeric operations. Example: var number = aString - 0: converts aString to number.

Introduction System Software. Copyright Teodor Rus – p.53/59

Parser Methods parseInt(), parseFloat()

convert their string arg to int/float literals.

Introduction System Software. Copyright Teodor Rus – p.54/59

Assignment Statements Are exactly as the assignment in C like languages. Examples:

a = 7; a += 7; a = a + 7.

Remember:

JavaScript has two kinds of vales: primitives and objects.

• When a variable refer to an object, the value of variable is an address. • Consequently, assigning an object to a variable is fundamentally different from assigning a primitive value to a variable.

Introduction System Software. Copyright Teodor Rus – p.55/59

Control Statements • Control statements often require some syntactic container for sequences of statements whose execution they are meant to control; • The container is the Compound statement which in JavaScript is a sequence of statements delimited by braces (as in C); • Control construct: is a control statement and the statement or compound statement whose execution it controls. • Control statement is composed from a control expression and a mechanism of flow selection.

Introduction System Software. Copyright Teodor Rus – p.56/59

Control Expressions Include primitive values, relational expressions, and compound expressions. Result of evaluating a control expression is true or false. • If the value is a string, it is interpreted as true, unless it is the empty string "" or zero string "0". • If the value is a number, it is true unless it is zero (0). Although: NaN, undefined, and null are all interpreted as false.

Introduction System Software. Copyright Teodor Rus – p.57/59

Relational Operators Relational operators are: • ==, ! =, , =, ===, ! == interpreted as in C. Note: if two operands are not of the same type and operator is not === or !==, JavaScript will attempt to convert them to the same type

• Comparisons of variables that reference objects are rarely useful; if a and b references different objects a == b is true only if a and b reference the same object;

• Boolean operators: &&(AND), ||(OR), !(NOT) where && and || are short-circuit operators.

Introduction System Software. Copyright Teodor Rus – p.58/59

Precedence and Associativity The following table shows the precedence and associativity of JavaScript operators, where highest-precedence operators are listed first. Operators

Associativity

++,–,unary -

right

*, /, %

left

+, -

left

=

left

==, !=

left

===,!==

left

&&

left

||

left

=, + =, − =, ∗ =, / =, && =, || =, & =

right

Introduction System Software. Copyright Teodor Rus – p.59/59