290 likes | 311 Views
Overview JavaScript. (Recommended Reading : Programming the World Wide Web, 4 th 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)
E N D
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 program • Object has no data properties, but several method properties
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 class • Objects are built on-the-fly
Built-in Objects • There are objects corresponding to the 3 data primitives • Number, String, Boolean • (note the upper case first letter) • These wrap a single value and provide some methods • One 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);
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
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 demoStringToHtml.html
Object Conversions • 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( )
Other Built-in Objects • Math • Like Java Math • No instance needed – all constants and methods referenced through the Math object • Constants • 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)
Other Built-in Objects • Date vardt = 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 string • toString( ) • toGMTString( ) – converts to a string according to Greenwich time. • toLocaleString( ) date.html
Arrays • JS has arrays which look like Java arrays • Standard variable names to reference Array objects • Indexed 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 literalvar newAr = [“one”, 2, “three”]; • Note the square brackets, not braces • Note that values of different data types can be mixed
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 undefined a[100] = 2; // has only 1 defined
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 array • sort( ) – converts elements to strings, sorts them alphabetically (or you can specify another order as a function); affects calling array • push( ), pop( ) – add/delete elements to the high end of array • unshift( ), shift( ) – add/delete elements at the beginning of the array
Associative 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]); demoArrays.html
Functions • 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
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;}
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
Functions • Functions used like Java methods • Calculations • Data checking • Any process you do more than once or want to isolate • Note: a function definition should precede calls to the function, to guarantee it is loaded before being called → usually placed in head section
Functions • 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 demoFunctionArgs.html
Functions • JS uses pass-by-value parameter-passing method • Primitives 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
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 executes • However, 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 (vari=0; i<arguments.length; i++) document.write(arguments[i] + “<br />”);
User-defined Objects, Creation&Modification • The new expression is used to create an object: • This includes a call to a constructor method • The 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.
User-defined Objects, Creation&Modification • Properties are not variables, they are just the names of values, so they are not declared • An 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
User-defined Objects, Dynamic Properties • Create my_car and add some properties // Create an Object object with no properties var my_car = new Object(); // Create and initialize the make property my_car.make = "Ford"; // Create and initialize the model property my_car.model = "Contour SVT"; • The delete operator can be used to delete a property from an object • delete my_car.model
The for-in Loop • 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: Ford Name: model; Value: Contour SVT
Functions are Objects • 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
Constructors • 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 demoConstructor.html
Constructors • Object methods are properties that refer to / point to functions • A 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…
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
Errors in Scripts • JavaScript errors are detected by the browser • Different browsers report this differently • Firefox uses a special console • IE dbl click =>