Overview JavaScript
description
Transcript of Overview JavaScript
1
Overview JavaScript(Recommended Reading : Programming the World Wide Web, 4th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
JavaScript Objects Objects are collections of properties (equivalent to
members of classes in Java) Properties are either data properties or method
properties Data properties are either primitive values or
references to other objects Subprograms called through objects are called
methods, subprograms not called through objects are called functions
The Object object is the ancestor (through prototype inheritance) of all objects in a JavaScript programObject has no data properties, but several method properties
2
JavaScript Objects JS has built-in objects
E.g. Math, Date Browser creates objects
These model the document (web page) You can create your own objects
But JS has no classObjects are built on-the-fly
3
There are objects corresponding to the 3 data primitivesNumber, String, Boolean(note the upper case first letter)
These wrap a single value and provide some methodsOne method all three wrapper objects have is
valueOf() - returns the corresponding primitive value of an object
Create an object with new: var doneObj = new Boolean(true); var numObj = new Number(3.14159);
4
Built-in Objects
Boolean has no useful methods of its own Number has formatting methods
toExponential(digitsAfterDP) - converts the value of the object into an exponential notation with the # requested digits after .var num = new Number(10000); document.write (num.toExponential(1));writes into document 1.0e+4
toPrecision(numberOfDigits) - converts a number into a number with the specified number of digits
toFixed(digitsAfterDP) - rounds the number to the specified number of decimal places
5
Built-in Objects
String has many methods Many are the same as for Java String object
indexOf, charAt, substring, etc. (we discussed some of these) Also has methods to create HTML strings
var st = new String(“I’m big and bold!”); var st1 = st.bold(); var out = st1.big();gives <big><bold>I’m big and bold!</bold></big>
See http://www.w3schools.com/jsref/jsref_obj_string.aspfor a complete reference
6
Built-in Objects
demoStringToHtml.html
JS does many automatic conversions between primitives and objects
Previous example could be written:
var st = “I’m big and bold!”; var out = st.big().bold();
In this case, the variable st is automatically converted to a String object to make the first method call and the resulting string is then converted to a String object to call bold( )
7
Object Conversions
MathLike Java MathNo instance needed – all constants and methods
referenced through the Math objectConstants
○ Math.PI. Math.SQRT2, etc.Methods
○ Trig functions: Math.sin( ), etc.○ Number manipulation: Math.floor( ), Math.min( ),
Math.round()○ Calculational: Math.pow( ), Math.exp( ), Math.random( ) -
like Java: [0, 1)
8
Other Built-in Objects
Datevar dt = new Date( );
gives the current date Date has getX and setX methods for X =
FullYear, Month, Day, Hours, Minutes, Seconds and Milliseconds
Formatting methods return date as a stringtoString( )toGMTString( ) – converts to a string according
to Greenwich time.toLocaleString( )
9
Other Built-in Objects
date.html
JS has arrays which look like Java arraysStandard variable names to reference Array objectsIndexed with [ ]
JS arrays are objects!Can be created with new keyword
var newAr = new Array(“one”, “two”, “three”, 4); var newAr = new Array(3);
1st way creates and initializes array (> 1 argument)2nd way just sets size (1 int argument)
Can also be created with array literal var newAr = [“one”, 2, “three”];Note the square brackets, not bracesNote that values of different data types can be mixed
10
Arrays
Array elements are accessed as in Java: var first = newAr[0];
Can be multi-dimensional as in Java .length property gives the current length
= the highest subscript to which a value has been assigned + 1, or the initial size, whichever is larger
Can be read or written Arrays are not fixed in length
By setting new array elements using an index beyond the current length, or by setting the length property to a larger value you extend the array (very much NOT like Java)
By setting the length property to a smaller value you shrink the array Space is not reserved for each element, only those defined
(assigned)var a = new Array(5); // all are undefineda[100] = 2; // has only 1 defined
11
Arrays
Flexibility of arrays allows many methods; var list = [2, 4, 6, 8, 10]
slice() – returns part of an array: list.slice(1,3) => array [4, 6]concat( ) – concatenates new elements to the end of the array;
returns new array: list.concat(12) => [2, 4, 6, 8, 10, 12]join( ) – creates a string from the array elements, separated by
commas (or specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10” reverse( ) – reverses order of the array elements; affects calling
arraysort( ) – converts elements to strings, sorts them alphabetically (or
you can specify another order as a function); affects calling arraypush( ), pop( ) – add/delete elements to the high end of arrayunshift( ), shift( ) – add/delete elements at the beginning of the
array
12
Arrays
Array with non-numeric indices Also called a hash Created as Object and filled using index
value
var myHash = new Object();myHash[“me”] = “Instructor”;myHash[“you”] = “Student”;for (var i in myHash)
alert (i + "-" + myHash[i]);
13
Associative Arrays
demoArrays.html
Several types of JS functions exist We will focus on simple declarative functions
Like Java methods Defined with keyword function Parameters follow in parentheses
No parameter types required() required even if no parameters are declared
Body of function in brackets (=compound statement) Function terminates at end } or with return statement No return type is declared
Function can return a value of any type or have no return value
14
Functions
Example:
function greet(hour, name) { if(hour < 12)
document.write(“Good morning, “+name); else if(hour < 18) document.write(“Good afternoon, “+name); else if(hour < 24) document.write(“Good evening, “+name); else return false;}
15
Functions
Note that the example function may or may not return a value.If no value is returned explicitly from function, the undefined
value is return by default○ Could test by:
var result = greet(hour, name); if(result != undefined) document.write(“Wrong hour”);
○ Note: no quotes on undefined
16
Functions
Functions
Functions used like Java methodsCalculationsData checkingAny process you do more than once or want to
isolateNote: a function definition should precede calls to
the function, to guarantee it is loaded before being called → usually placed in head section
17
Formal parameters are local variables All other local variables must be declared with var or else a
global variable may be used Data types of arguments are not checked – just converted as
needed
18
Functions
demoFunctionArgs.html
JS uses pass-by-value parameter-passing methodPrimitives are passed by value
Changing the value in the function has no effect at the calling site
Objects are passed by reference
Changing the object in the function changes the caller’s object
19
Functions
Functions Number of arguments passed to a function is not
checked against the number of formal parameters in the called function
Excess actual parameters are ignored (however, see below)
Excess formal parameters are set to undefined○ i.e. if you define function f(a, b, c) and call it by f(p, q)
then c will be undefined when f executesHowever, a property array named arguments holds all
of the actual params, whether or not there are more of them than there are formal params:
for (var i=0; i<arguments.length; i++) document.write(arguments[i] + “<br />”);
20
The new expression is used to create an object:This includes a call to a constructor methodThe new operator creates a blank (empty) object, the constructor
creates and initializes all properties of the object
Properties of an object (data and methods) are accessed using a dot notation: object.property; or the object[property] notation.
21
User-defined Objects, Creation &
Modification
User-defined Objects, Creation & Modification
Properties are not variables, they are just the names of values, so they are not declaredAn object may be thought of as a
Map/Dictionary/Associative-Storage
The number of properties of an object may vary dynamically in JS; properties can be added/deleted from an object at any time during interpretation
22
Create my_car and add some properties// Create an Object object with no propertiesvar my_car = new Object();// Create and initialize the make propertymy_car.make = "Ford";// Create and initialize the model propertymy_car.model = "Contour SVT";
The delete operator can be used to delete a property from an objectdelete my_car.model
23
User-defined Objects, Dynamic Properties
Syntax: for (identifier in object)statement or compound statement
The loop lets the identifier take on each property (name) in turn in the object
Printing the properties in my_car:for (var prop in my_car)document.write("Name: " + prop + "; Value: " +
my_car[prop] + "<br />");
Result: Name: make; Value: FordName: model; Value: Contour SVT
24
The for-in Loop
Functions are objects in JavaScript
Functions may, therefore, be assigned to variables and to object properties Object properties that have function values are methods of the object
Example:
function fun() {
document.write("This surely is fun! <br/>");
}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun
25
Functions are Objects
Constructors are functions that create and initialize properties for new objects; have same name as object being created
A constructor uses the keyword this in the body to reference the object being initialized
26
Constructors
demoConstructor.html
Constructors
Object methods are properties that refer to / point to functionsA function to be used as a method may use
the keyword this to refer to the object for which it is acting
As in Java, the JavaScript user-defined objects can be quite powerful and quite complicated…
We won’t really need to use them for form verification…
27
Development of JavaScript
To run JavaScript code, you may need to change the browser’s security settings.
IE 7 prevents by default scripts on your local computer from running;
Check the “Allow active content to run in files on MyComputer” box in Tools / Internet options / Advanced / Security
Firefox has JavaScript enabled by default
28
Errors in Scripts JavaScript errors are detected by the browser Different browsers report this differently
Firefox uses a special console
IE dbl click =>
29