overview of javascript

53
Overview of JavaScript •Developed by Netscape, as LiveScript •Became a joint venture of Netscape and Sun in 1995, renamed JavaScript •Now standard of the European Computer Manufacturers Association ECMA-262 (also ISO 16262)

Upload: selia

Post on 06-Jan-2016

27 views

Category:

Documents


0 download

DESCRIPTION

Overview of JavaScript. Developed by Netscape, as LiveScript Became a joint venture of Netscape and Sun in 1995, renamed JavaScript Now standard of the European Computer Manufacturers Association ECMA-262 (also ISO 16262). JavaScript. Three categories - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Overview of JavaScript

Overview of JavaScript

•Developed by Netscape, as LiveScript

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

•Now standard of the European Computer Manufacturers Association

ECMA-262 (also ISO 16262)

Page 2: Overview of JavaScript

JavaScript

• Three categories Core, Client-side, & Server-side

• Collections of JavaScript code as called scripts• Java and JavaScript only related through syntax

JavaScript is dynamically typed JavaScript's support for objects is very different

• JavaScript can be embedded in many things, but its primary use is in HTML

Page 3: Overview of JavaScript

JavaScript

• Document Object Model (DOM)

Supports dynamic HTML with JavaScript• Promotes user interaction through forms• User interactions with HTML documents in

JavaScript use the event-driven model of computation User interaction with form elements can be used to

trigger scripts

Page 4: Overview of JavaScript

OO & JavaScript

• JavaScript is not OO programming language Does not support class-based inheritance

Cannot support polymorphism

Prototype-based inheritance Which is much different

Page 5: Overview of JavaScript

JavaScript Objects

• Objects are collections of properties (like members of the class in Java) Data properties Method properties

• Primitives for simple types• JavaScript objects are accessed through references• Objects appear as lists of property-value pairs

Properties can be added or deleted dynamically

Page 6: Overview of JavaScript

JavaScript General Syntax

• Embedded in HTML documents Directly as the content of <script> tag

<script language =”JavaScript” > ... </script>

Indirectly as a file specified in the src attribute of <script> tag

<script language =”JavaScript” src=myscript.js”> ... </script>

Page 7: Overview of JavaScript

JavaScript General Syntax

• Place scripts inside HTML comments to hide them from browsers that do not include JavaScript interpreters

• Statements do not need to be terminated by ; But it is a good practice to do so

Page 8: Overview of JavaScript

Primitives, Operations & Expressions

• Primitive values, one of five:

Number, String, Boolean, Undefined, or Null• Number, String, and Boolean have wrapper

objects: Number, String, & Boolean• Primitive values and objects of Number & String

are coerced back and forth Primitive values are treated essentially as if they were

objects

Page 9: Overview of JavaScript

Primitives, Operations & Expressions

• Numeric literals are just as in Java• Numeric values are stored in double-precision

floating point• String literals are delimited by ' ' or “ “

Can include escape sequences (\t) Embedded variable names are not interpolated String literals are primitive values

Page 10: Overview of JavaScript

Primitives, Operations & Expressions

• Boolean values are true and false• The only value of Null is null• The only Undefined value is undefined• JavaScript is dynamically typed

Any variable can be used for any thingPrimitive value or reference to any objectThe interpreter determines type of each

occurrence of a variable

Page 11: Overview of JavaScript

Primitives, Operations & Expressions• Variables declared explicitly or implicitly

var = sum = 0,

today = “Monday”,

flag = false ;• Numeric operators: ++, - -, +, -, *, /, %

All in double precision• The Math object

Floor, round, max, min, trig functions, etc.• Assignment operator – Just like Java

Page 12: Overview of JavaScript

Primitives, Operations & Expressions

The Number object with method toString Some useful properties:

MAX_VALUE, MIN_VALUE, NaN,

POSITIVE_INFINITY, NEGATIVE_INFINITY, PI Number .MAX_VALUE

Arithmetic operation creates overflow returns NaN NaN is not == to any other number, not even itself Test for it with is NaN(x)

Page 13: Overview of JavaScript

Primitives, Operations & Expressions

String catenation operator: + Coercions:

Catenation coerces numbers to strings Numeric operators (not +) coerce strings to numbers

Conversions from strings to numbers that do not work return NaN

Page 14: Overview of JavaScript

Primitives, Operations & Expressions

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 15: Overview of JavaScript

Primitives, Operations & Expressions

Conversion functions (not called through string objects, because these are not methods)

parseInt(string) and parseFloat(string) String must begin with a digit or a sign and contain

a legal number, otherwise NaN is returned The typeof operator

Returns “number, “string”, or “boolean” for primitives

Returns “object” for objects and null

Page 16: Overview of JavaScript

Screen Output

The Document object is the JavaScript model for the HTML document

The Window object in the model for the browser display window Two properties: document, and window

Referring to Document and Window objects

Page 17: Overview of JavaScript

Screen Output

The Document object has a method, write, Dynamically creates content Parameter is a string that is sent to the browser

it can be any thing that can appear in HTML including tags

Parameter often catenated from parts some of which are variables

document.write(“It is OK” + “to learn about” +

“<br />”) ;

Page 18: Overview of JavaScript

Screen Output

The Window object has three methods alert, confirm, and prompt The default object is the current window

Object need not be included in calls to any of these Alert( “ Hello World! \n”)

Parameter plain text, not HTML Opens a dialog box which displays the parameter string and

an OK button Waits for used to press the OK button

Page 19: Overview of JavaScript

Screen Output

Confirm (“What would you like?”) Opens a dialog box, displays the parameter and

two buttons, OK and cancel Returns a Boolean

prompt(“What is your pleasure?”,””) Opens a dialog box, displays the parameter, along

with a text box and two buttons, OK and cancel The second parameter is for default value if the

user presses OK without typing any response

Page 20: Overview of JavaScript

Control Expressions

Primitive Values If it is string, it is true unless it is empty or “0” If it is a number, it is true unless it is zero

Relational Expressions: ==, !=, <, >, >=, >= Operands coerced if necessary

String to number / Boolean to number Unusual: ===, !==

Same as == and !=, except that no coercions are allowed. Operands must be identical

Page 21: Overview of JavaScript

Control Expressions

Compound expressions &&, ||, and ! Primitive values, true and false, not to be confused

with Boolean Object properties Boolean object in a expression is false only when it is null

or undefined Boolean object has a method, toString, to allow them to be

printed out.

Page 22: Overview of JavaScript

Selection Statements

If-then-else --Just as in Java Switch

switch (expression) {

case value_1:

// value_1 statements

case value_2:

// value_2 statements

[default: // default statements]

}

Page 23: Overview of JavaScript

Control Statements

Loop Statements while(control_expression)

Statement or compound

For( int ; control ; increment)

Statement or compound Int can have declaration, but scope is the whole script

do

Statement or compound

while( control_expression)

Page 24: Overview of JavaScript

Object Creation/Modification

Objects created with new Most basic object uses the object constructor

Var myobject = new object();

New object has no properties - a blank object Properties can be added to object at any time

var mycar = new object();

mycar.make = "volvo";

mycar.model = "240";

Page 25: Overview of JavaScript

Object Creation/Modification

Objects can be nested. A property can be itself another object created with new.

Var property1 = mycar["model"];

Attempting to access non-existing properties yields undefined

Properties can be deleted with delete:

delete mycar.model;

Page 26: Overview of JavaScript

Object Creation/Modification

The for-in loop-statement is perfect for listing the properties of an object:

for( identifier in object)statement or compound

Ex:

for( var prop in mycar)

document.write(mycar[prop] +"<br />");

Page 27: Overview of JavaScript

Arrays Objects having some special functionality Array elements can be primitive values or

references to other objects. Array objects can be created in two ways:

With new:

var mylist = new Array(24,"butter", false);//length is 3.

var mylist2 = new Array(24) /* length is 25 */

Assigning an array literal:

var mylist3 = [24, "eggs", false];

Page 28: Overview of JavaScript

Arrays Length is dynamic -length property stores it. Length is highest subscript to which an element

has been assigned, plus 1

mylist[122] = "wee-small"; // length is 123

length property is writeable

mylist.length =150; //make it larger

mylist.length = 2; //make it shorter

Only assigned elements take up memory spacehttp://www.ens.utulsa.edu/~class_diaz/cs2043/insert_names.html

Page 29: Overview of JavaScript

Array Methods

var list = new Array("John","Paul","George","Ringo");

join - var listStr = list.join(": ");listStr contains "John: Paul: George: Ringo"

reverse sort -coerces elements to strings and puts them

in alph order concat - newList = list.concat(47,26);

Page 30: Overview of JavaScript

Array Methods

slice

listPart = list.slice(1,3); // listPart is ["Paul","Ringo"]

listPart = list.slice(2); // listPart is ["George","Ringo"]

toString -- exactly as join(", ") push, pop, unshift, shift

http://www.ens.utulsa.edu/~class_diaz/cs2043/nested_arrays.htm

Page 31: Overview of JavaScript

JavaScript Functions

function function_name( formal_arguments){

... // function_body

} A return statement turns control to caller.

A function returns undefined when: End of the function is reached, or Specific return statement executed does not have

expression There are no return statements in the function

Page 32: Overview of JavaScript

Functions

Functions are objects! Variables that reference them can be treated as any

other object reference: Can be passed as parameters, Can be assigned variables, Can be elements of an array

ref_fun = fun; // where fun is the name of a function

/* ref_fun is a reference to fun*/

ref_fun(); /* A call to fun */

Page 33: Overview of JavaScript

Functions

All variables declared, implicitly or explicitly, outside functions have global scope.

Variables explicitly declared in a function have local scope.

Local variables have precedence over global variables with the same name.

Functions can be nested - we will not discuss it.

Page 34: Overview of JavaScript

Function Parameters

JavaScript functions parameters are normally passed-by-value.

There is not type checking of parameters. There is no checking on the number of

parameters:excess actual parameters are ignored

excess formal parameters are set to undefined.

Page 35: Overview of JavaScript

Function Parameters

All parameters passed through a property array, arguments. A function can determine the number of actual

parameters by accessing arguments.length Because the arguments array is accessible directly, all

actual parameters in the call are available, including the actual parameters that do not correspond to any formal parameters

http://www.ens.utulsa.edu/~class_diaz/cs2043/parameters.htm

Page 36: Overview of JavaScript

Function Parameters

When a reference is passed, the function has access to objects in the calling program. Hence it can also pass-by-reference objects.

There is no clean way to send a primitive by reference

Function by10(a){a[0]*=10;}...Var listx = new Array(1);Listx[0] = x;By10[listx);

X = list[0];

Alternative, function returns the new value.

Page 37: Overview of JavaScript

The sort method Sort method coerces elements to strings and puts

them in alph order. To sort something other than strings to alpha ord,

write a function that performs the comparison and send it to the sort method.

The comparison must return a negative number if the two numbers are in order, zero if they are equal, positive number if they are not.

Function num_order(a, b) {return a-b;}

num_list.sort(num_order);

Page 38: Overview of JavaScript

Median of a list

function median( list){

list.sort(function(a,b){return a-b;});

var list_len = list.length;

if (( list_len %2 == 1 )

return list[Math.floor(list_len / 2)];

else

return Math.round( (list[list_len /2 -1]+

list[list_len /2 ] ) / 2 );

} // End of function median.

http://www.ens.utulsa.edu/~class_diaz/cs2043/medians.html

Page 39: Overview of JavaScript

Constructors

Methods that create and initialize properties of newly created objects

Constructors are called by the new operator which precedes them in the new expression

var array = new Array(100);

Constructor references the object with this, a predefined reference variable used to construct and initialize the properties of the object.

Page 40: Overview of JavaScript

Constructors

Example

function car(new_make, new_model, new_year){

this.make = new_make;

this.model = new_model;

this.year = new_year;

}

my_car = new car("Volvo", "S90", "2002");

Page 41: Overview of JavaScript

Constructors

Methods for the objects are initialized just as if it were a data property:

function display_car(){

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

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

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

Add to the constructor: this.display = display_car;

Now call method: my_car.display();

Page 42: Overview of JavaScript

Pattern MatchingRegular Expressions

Pattern matching based on the RegExp object are not covered in this class.

Pattern matching based on methods of the String object are covered.

Methacharacters have special meaning in some contexts in patterns:

\ | ( ) [ ] { } ^ $ * + ? .

Normal characters are not methacharacters.

Page 43: Overview of JavaScript

Pattern Matching

search(pattern) Returns position in the string object where the pattern

matched

var str = "Hurricane";

var position = str.search(/can/);

/* position is now 5 */

If there is no match it returns-1 The period matches any character except new line.

/snow./ matches "snowy", "snowd", etc.

Page 44: Overview of JavaScript

Pattern Matching

Placing desired characters in brackets allows class of characters

[abc] matches for 'a', 'b', or 'c'

[a-h] matches any lower case letter from 'a' to 'h'

[^aeiou] matches any consonant

Repeated character or character-class pattern

/xy{4}z/ matches for xyyyyz

Page 45: Overview of JavaScript

Pattern Matching Predefined Character Classes

\d [0-9] A digit

\D [^0-9] Not a digit

\w [A-Za-z_0-9] An alphanumeric character

\W [^A-Za-z_0-9] Not an alphanumeric

\s [ \r\t\n\f] A whitespace character

\S [^ \r\t\n\f] Not a whitespace character

\b matches boundary between \w and \W

\B matches a non-word boundary, opposite of \b

Page 46: Overview of JavaScript

Pattern Matching

Symbolic quantifiers

* zero or more repetitions

+ one or more repetitions

? one or none repetitions

/x*y+z?/ any number of xs, one or more y, may be a z

/\d+\.\d*/ a string of one or more digits followed by a decimal period and may be more digits.

Page 47: Overview of JavaScript

Pattern Matching

Anchors Beginning of string (^):

/^pearl/ matches patterns beginning with "pearl ..."

Ending of string ($):

/gold$/ matches patterns ending in " ... gold"

Note anchor characters only have such meaning in these locations:

/A^is$/ matches for /A^is$/ only

Page 48: Overview of JavaScript

Pattern Matching

Modifiers attached to patterns to change how they are used:

/ab/i matches for either upper or lower case 'ab'

/sp/x allows for white space to appear in the pattern

Page 49: Overview of JavaScript

Pattern Matching

replace (pattern, string) Replace substrings in the string object that match

pattern.

Var str = "It rains mostly in the plains";

str.replace(/in/g, "nk");

/* str becomes "It ranks mostly nk the planks" */

$1, $2, $3 predifined variables set to "in"

g modifier makes replacement global, every match replaced.

Page 50: Overview of JavaScript

Pattern Matching

match(pattern)

Returns array of results of pattern-matching operation With the g modifier it returns an array of substrigs that

matched Without the g modifier, first element of returned array has

the matched substring, the other elements have the values of $1, ...var str "my 3 kings beat your 2 aces";var matches = str.match(/[ab]/g);/* matches is set up to ["b", "a", "a"]

Page 51: Overview of JavaScript

Pattern Matching

Split(pattern) --splits object string into substrigs based on a given pattern

var str = "gouda:brie:raclet";

var cheese = str.split(":");

/* cheese set to [gouda, brie, raclet] */

http://www.mcs.utulsa.edu/~class_diaz/cs2043/forms_check.html

Page 52: Overview of JavaScript

Debugging JavaScript

IE6 Select Internet Options from the Tools menu Choose the Advance tab Uncheck the Disable script debugging box Check the Display a notification about every script error box

Now a window error causes a small window to be opened with an explanation of the error

Page 53: Overview of JavaScript

Debugging JavaScript

NS6 Select Tasks, Tools, and JavaScript Console

A small window appears to display script errors To avoid confusion, clear the console after using an

error message.