
JavaScript • Interpreted programming language with OO capabilities • Core syntax resembles C, C++ and JAVA • However: – Loosely typed - variables do not need to have a type specified JavaScript Elements – JS Objects are more like hash tables or associative arrays than they are like structs (C) or objects (C++, Java) – OO inheritance is prototype-based – Draws inspiration from Perl in regular expressions and array- handling features 2 Overview of JavaScript Overview of JavaScript • Originally developed by Netscape, as LiveScript • JavaScript can be used to: – replace some of what is typically done with applets (except • Became a joint venture of Netscape and Sun in graphics) 1995, renamed JavaScript – replace some of what is done with CGI - namely server-side • Now standardized by the European Computer programming (but no file operations or networking) Manufacturers Association as ECMA-262 (also • User interactions through forms are easy ISO 16262) • The Document Object Model makes it possible to support dynamic HTML documents with JavaScript • We’ll call collections of JavaScript code scripts, – Much of what we will do with JavaScript is event-driven not programs computation http://www.ecma-international.org/publications/standards/Ecma-262.htm 3 4 Object Orientation and JavaScript JavaScript and JAVA • JavaScript is NOT an object-oriented programming • JavaScript and Java are only related through syntax language • JAVA is strongly typed - types are known at compile time – Does not support class-based inheritance - cannot support and operand types (τύποι τελεστέων) are checked for polymorphism compatibility – Has prototype-based inheritance, which is much different • Variables in JavaScript are dynamically typed • JavaScript objects are collections of properties, which are – Compile-time type checking impossible like the members of classes in Java and C++ • Objects in JAVA are static: • JavaScript has primitives for simple types – their collection of data members and methods is fixed at • The root object in JavaScript is Object – all objects are compile time derived from Object • JavaScript objects are dynamic: – members of an object can change during execution • All JavaScript objects are accessed through references 5 6 Browsers and HTML/JavaScript Documents Implicit vs Explicit JavaScript • What happens when the browser encounters a JavaScript • Explicit embedding: script in a document? – Mixes two types of notation inside the same document (bad • Two approaches for embedding JavaScript in HTML for readability) documents: – Makes maintenance difficult - often different people manage – Explicit embedding (ρητή ενσωμάτωση) the HTML and the JavaScript <script type = "text/javaScript"> • Depending on its use, a JavaScript script that is explicitly -- JavaScript script – embedded appears in: </script> – The head of an HTML document - for scripts that produce – Implicit embedding (υπόρρητη ενσωμάτωση) content only upon request or for those that react to user <script type = "text/javaScript" interactions src = "myScript.js"> • These scripts contain function definitions and code associated with form </script> elements – The body of an HTML document - for scripts that are to be interpreted just once, as they are found 7 8 JavaScript embedding JavaScript objects • Scripts are usually hidden from browsers that • Objects are collections of properties: do not include JavaScript interpreters by putting – data properties (primitive values and references to objects) them in special comments: – method properties (methods) <!-- • Objects are accessed indirectly through variables -- JavaScript script – – The properties of an object are referenced by attaching the name of a property to the variable that references the //--> object. E.g. myCar.engine • This is also required by the HTML validator • Objects are dynamic collections of property-value pairs • Note that the comment closure is in a new line and – Properties are names – is also a JS comment Values are data values or functions • All functions are objects and are referenced through variables 9 10 JavaScript objects Client-Side JavaScript <?xml version="1.0" encoding="UTF-8" ?> • An object can represent: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// – www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Unordered collection of named values <html xmlns="http://www.w3.org/1999/xhtml"> – Ordered collection of numbered values: array <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> – An entity that has executable code associated with it: <title>This is a test on Javascript and HTML</title> </head> function <body> <h2>The Table of factorials</h2> • Because these three kinds of objects behave differently, <script> we treat them as distinct datatypes <!-- var fact=1; • There are also specialised objects which represent new for (i=1;i<10;i++) { classes of objects: fact = fact*i; document.write(i + "! =" + fact + "<br>"); – Date } – RegExp //--> – </script> Error </body> </html> 11 12 General Syntactic Characteristics Primitives, Operations, Expressions • Identifier: simply a name, used to: • Boolean values are true and false – name variables and functions • The only Null value is null – provide labels for certain loops – syntax same as Java: • The only Undefined value is undefined • begin with a letter or underscore, followed by any number of letters, • JavaScript is dynamically typed underscores, and digits – • case sensitive any variable can be used for anything (primitive value or reference to any object) • Comments: both // and /* … */ – The interpreter determines the type of a particular occurrence of a variable (values do have type) • Variables can be either implicitly or explicitly declared var sum = 0, today = "Monday", flag = false; 13 14 Primitives, Operations, Expressions Primitives, Operations, Expressions • Numeric operators - ++, --, +, -, *, /, % • Primitives, Operations, & Expressions (continued) – – All operations are in double precision String catenation operator : + – Coercions (implicit type conversions) – Same precedence and associativity as Java – Catenation coerces numbers to strings • The Math Object provides floor, round, max, min, trig – Numeric operators (other than +) coerce strings to numbers (if either operand of functions, etc. e.g., Math.cos(x) + is a string, it is assumed to be catenation) – Conversions from strings to numbers that do not work return NaN • The Number Object collects useful properties that have constant • Explicit conversions values – Use the String and Number constructors – Some useful properties: – Use toString method of numbers – • MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY, Use parseInt and parseFloat on strings PI • String properties & methods: • e.g., Number.MAX_VALUE – length e.g., var len = str1.length; (a property) • An arithmetic operation that creates overflow returns NaN – charAt(position) e.g., str.charAt(3) – NaN is not 55 to any number, not even itself – indexOf(string) e.g., str.indexOf('B') – Test for it with isNaN(x) – substring(from, to) e.g., str.substring(1, 3) – toLowerCase() e.g., str.toLowerCase() • Number object has the method, toString 15 16 Primitives, Operations, Expressions Screen output and keyboard input • The typeof operator • JavaScript models the HTML document inside which a script – Returns "number", "string", or "boolean" for Number, String, or Boolean, "undefined" for Undefined, "function" for functions, and "object" for is embedded, as a Document object objects and for NULL • The model for the browser display window is the Window • Assignment statements – just like C++ and Java object • The Date Object – The Window object has two properties, document and window, – Create one with the Date constructor (no params): var today = new Date(); which refer to the Document and Window objects, respectively – Local time methods of Date: (window is self-referential) • toLocaleString – returns a string of the date – The Document object has a method, write, which dynamically • getDate – returns the day of the month creates content • getMonth – returns the month of the year (0 – 11) • getDay – returns the day of the week (0 – 6) • Its parameter is a string, often catenated from parts, some of • getFullYear – returns the year which are variables e.g., • getTime – returns the number of milliseconds since January 1, 1970 document.write("Answer: " + result + "<br / • getHours – returns the hour (0 – 23) >"); • getMinutes – returns the minutes (0 – 59) • The parameter is sent to the browser, so it can be anything that can • getMilliseconds – returns the millisecond (0 – 999) appear in an HTML document (<br />, but not \n) 17 18 Screen output • The Window object has three methods for creating dialog boxes: – alert, confirm, and prompt Window • alert("Hej! \n"); – Parameter is plain text, not HTML – Opens a dialog box which displays the parameter string and an OK button – It waits for the user to press the OK button • confirm("Do you want to continue?"); Document – Opens a dialog box and displays the parameter and two buttons, OK and Cancel – Returns a Boolean value, depending on which button was pressed (it waits for one) • prompt("What is your name?", ""); – Opens a dialog box and displays its string parameter, along with a text box and two buttons, OK and Cancel – The second parameter is for a default response if the user presses OK without typing a response in the text box (waits for OK) 19 20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages14 Page
-
File Size-