1 / 53

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). JavaScript. Three categories

carol
Download Presentation

Overview of JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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)

  2. 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 embeded in many things, but its primary use is in HTML

  3. JavaScript • DocumentObject Model (DOM) makes it possible to support 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

  4. OO & JavaScript • JavaScript is not OO programming language • Does not support class-based inheritance • Cannot support polymorphism • Prototype-based inheritance • Which is much different

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

  6. JavaScript General Syntax • Embeded 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 <script language =”JavaScript” src=myscript.js”> ... </script>

  7. JavaScript General Syntax • Place scripts inside HTML comments to hide them from bowsers that do not include JavaScript interpreters • JavaScriot does not need to be terminated by ; • But it is a good practice to do so

  8. 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

  9. 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 scape sequences (\t) • Embedded variable names are not interpolated • String literals are primitive values

  10. Primitives, Operations & Expressions • Boolean values are trueand 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 thing • Primitive value or reference to any object • The interpreter determines type of each occurrence of a variable

  11. 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 opperator – Just like Java

  12. 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 isNaN(x)

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

  14. 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()

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

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

  17. 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 />”) ;

  18. 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

  19. 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

  20. 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

  21. 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.

  22. 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] }

  23. 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)

  24. 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 = "245";

  25. 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;

  26. 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 />");

  27. 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];

  28. 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 space http://www.ens.utulsa.edu/~class_diaz/cs2043/insert_names.html

  29. 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);

  30. 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

  31. 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

  32. Functions • Functions are objects! • Variables that reference them can be treated as any other object reference: • Can be passed as paramenters, • 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 */

  33. 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.

  34. 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.

  35. 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

  36. 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.

  37. The sort method • Sort methodcoerces 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);

  38. 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

  39. 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 reterences the object with this, a predefined reference variable used to construct and initialize the properties of the object.

  40. 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");

  41. Constructors • Methods for the objects are initialized just as if it were a data property: function diplay_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();

  42. 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.

  43. Pattern Matching • search(pattern) • Returns position in the string object where the pattern matched var str = "Hurricane"; var position = str.search(/can/); /* postion is now 5 */ • If there is no match it returns-1 • The period matches any character except new line. /snow./ matches "snowy", "snowd", etc.

  44. 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

  45. 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

  46. 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.

  47. 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

  48. Pattern Matching • Modifiers attached to pattters 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

  49. 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.

  50. Pattern Matching • match(pattern) Returns array of results of pattern-maching operation • With the g modifier it returns an array of substrigs that matched • Whithout 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"]

More Related