Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)

Similar presentations


Presentation on theme: "1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)"— Presentation transcript:

1 1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)

2 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 2

3 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 3

4  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); 4 Built-in Objects

5  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

6  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 I’m big and bold!  See http://www.w3schools.com/jsref/jsref_obj_string.asp for a complete reference http://www.w3schools.com/jsref/jsref_obj_string.asp 6 Built-in Objects demoStringToHtml.htm l

7  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

8  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) 8 Other Built-in Objects

9  Date var 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 string toString( ) toGMTString( ) – converts to a string according to Greenwich time. toLocaleString( ) 9 Other Built-in Objects date.html

10  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); 1 st way creates and initializes array (> 1 argument) 2 nd way just sets size (1 int argument)  Can also be created with array literal var newAr = [“one”, 2, “three”]; Note the square brackets, not braces Note that values of different data types can be mixed 10 Arrays

11  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 11 Arrays

12  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 12 Arrays

13  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

14  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

15  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

16  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

17  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 17

18  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.htm l

19  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 19 Functions

20  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 (var i=0; i<arguments.length; i++) document.write(arguments[i] + “ ”); 20

21  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. 21 User-defined Objects, Creation & Modification

22  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 22

23  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 23 User-defined Objects, Dynamic Properties

24  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] + " ");  Result: Name: make; Value: Ford Name: model; Value: Contour SVT 24 The for-in Loop

25  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! "); } 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

26  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.ht ml

27 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… 27

28 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

29 Errors in Scripts  JavaScript errors are detected by the browser  Different browsers report this differently Firefox uses a special console IEdbl click => 29


Download ppt "1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)"

Similar presentations


Ads by Google