420 likes | 626 Views
Overview JavaScript. (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta , Chapters 4, 5 – available at Steely Library). Brief History. Originally developed by Netscape: Named LiveScript In 1995, Netscape & Sun Microsystems joined forces:
E N D
Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
Brief History • Originally developed by Netscape: • Named LiveScript • In 1995, Netscape & Sun Microsystems joined forces: • For marketing purposes, renamed it JavaScript • BUT IT IS NOT JAVA! • Microsoft countered with VBScript and JScript • European standards group ECMA (European Computer Manufacturers Association) created a standard specification for JavaScript in the late ‘90s; approved by the ISO (International Standards Organization) • ECMAScript → the official name of the standard language • Several versions exist • Supported by Firefox, Internet Explorer etc.
Purpose • A general-purpose programming language • Could be used for: • Client-side programming – a collection of objects supporting browser control and user interaction • Server-side programming – a collection of objects that make the language useful on web servers, ex. for communication with a DBMS • General programming • In fact, used most often for client-side scripting: • Adds programming capability to Web pages • Validate forms • Modify pages on the fly • Read/write cookies • Does not support however file operations, db access, networking
Implementation • JS is an interpreted language • Not compiled into machine or byte code • Source code is read when it is to be run, interpreted and executed • Interpreters are part of the browser • Browsers implement different features • Browsers may implement the same feature differently • Variations are greatest among older versions of browsers • JS vs. Java • JS has a different object model from Java: • based on object-prototypes, not on classes; • objects are dynamic, their properties & methods can change during execution • JavaScript is not strongly typed: • vars need not be declared & are dynamically typed (=assigned values of different types)
XHTML/JavaScript – Script Tag • JS code is embedded in XHTML using the <script> tag • JS code can be directly embedded in XHTML document = placed in-line up to </script> closing tag <script type=“text/javascript”> <!-- … Javascript here … //--> </script>
XHTML/JavaScript – Script Tag – or – • JS code can be indirectly embedded in XHTML document = URL of a JS code file can be added as a src= attribute • Still need the </script> closing tag <script type=“text/javascript” src=“tst_number.js”></script> • Also need type=“text/javascript” attribute
Location of JavaScript Code • Two locations for JavaScript code, different purposes: • Script that executes only when requested (function definitions) or that runs in response to an event (e.g. button push) can be put in the head section – the interpreter only notes the existence of these scripts, does not interpret them while processing the head • Scripts that are to be interpreted just once, as they are found, when page is loaded and interpreted, can be put in the body section • Various strategies must be used to ‘protect’ the JavaScript from the browser • For example, comparisons present a problem since < and > are used to mark tags in XHTML • JavaScript code can be enclosed in XHTML comments • JavaScript code can be enclosed in a CDATA section
Hiding In-line JavaScript(1) • If JS code contains recognizable XHTML tags (ex. <br /> in output of JS code), need to hide it from XHTML processors (like validators) • Use XHTML character data section → its content not parsed as XHTML <![CDATA[... JS goes here ….]]> • To hide this from JS interpreter, use JS comments: <script type=“text/javascript”> //<![CDATA[ or /*<![CDATA[*/ ... JS goes here …. //]]> or /*]]*/ </script> • The JS comment symbols do not bother the XML parser • The JS comment symbols protect the CDATA markers from the JS parser • Note the JS comments are: // for line comments, /* */ for multiline comments
Hiding In-line JavaScript(2) • A second technique is to use XHTML comments • Start in-line script with a comment <!-- or //<!-- • script is hidden from browsers that do not recognize the <script> tag and from XHTML validators • End script with a new line containing a JS comment followed by an XHTML comment // -- > (same explanation as before for the JS comment //) • Code looks like: <script type=“text/javascript”>//<!-- ... JS goes here …. // a-- ?!// --> </script>
Hiding In-line JavaScript(3) • Indirect reference to a JS file is the preferred approach. • What if no JS? • Can use <noscript> tag to provide alternate content for users that have disabled scripts in their browser or have a browser that doesn’t support client-side scripting. • All XHTML up to </noscript> is processed and displayed in this case. • Could be warning message, link to a static page, etc. <script type="text/javascript"> … </script> <noscript><p>Your browser does not support JavaScript!</p></noscript>
JavaScript Language • JS is an object-based language, not an object-oriented language • Has objects (that encapsulate both data and processing) and references, like Java • No general class definitions • Does not have true, class-based, inheritance; polymorphism; and subtyping • Has prototype-based inheritance: its objects serve both as objects and models of objects (http://en.wikipedia.org/wiki/Prototype-based_languages) • Has limited set of built-in objects; ex. objects that model documents and document elements • Can create “objects” on-the-fly
JavaScript Variable Names • Define names just like in Java • Best practice - start with a letter, not special character • Use CamelCase notation = write compound words in which the words are joined without spaces and are capitalized within the compound
JavaScript Variable Names • Can’t use reserved words – a larger set than Java • See http://javascript.about.com/library/blreserved.htm • JavaScript names are case sensitive
JavaScript Variables • Don’t have to be explicitly declared as in Java • Can just start using the variable in the code, to assign it a value – will be implicitly declared by the JS interpreter • But probably not a good idea and a source of subtle bugs: • JS can’t distinguish a typo from a new variable name… • All variables implicitly declared have global scope (=are global): can be accessed anywhere in the same file • Use keyword var to explicitly declare a variable • Variables explicitly declared outside functions are global • Variables explicitly declared inside functions are local to the function and hide global variables with same name • This assures no scope clashes: if outer block declares variable foo, an inner block that wants its own foo will use the value from the outer block if foo is not declared with var
JavaScript Variable Types • Note var doesn’t specify a type: var stop_flag = true, pi=3.14; • Variables can “change type” as program progresses, depending upon the value currently assigned to them → dynamically typed language • A variable can have a value of any primitive type, or it can be a reference to any object primitive and object storage • Programmer has to keep track of variable type if it matters
JavaScript Variable Types • 5 basic (primitive) types • string • numeric/number • boolean • undefined • null • Note that these aren’t keywords to declare type as in Java! • JS also includes predefined wrapper objects Number, String, and Boolean; • each contains only a property that stores a value of the corresponding primitive type • each provides useful methods to use with values of corresponding primitive type • JS converts automatically between primitive types and corresponding wrapper objects → methods of String object can be directly used on a variable storing a primitive string value
Other JS Primitive Types • null • A single value, null: keyword, indicates no value, can be assigned! • A variable that is used but not declared nor assigned a value has a null value • Using a null value usually causes a runtime error • Ex. if foo has not been declared: var value = foo + 2; • undefined • A single value, undefined; however undefined is not a keyword • Is the value of a variable declared but not initialized • Remains undefined until a value is assigned
Other JS Primitive Types • Can find the current data type of a variable via typeofoperator (evaluates to “number”, “string” or “boolean” for primitive operand, “object” for object or null operand, “undefined” for variable that has not been assigned a value) var i = 3; var typeString = typeof i; // note no ( ) are necessary, although can be used typeString will contain “number”
JS Constants • Declared with the const keyword const RETIREMENT_AGE = 65; const SCHOOL = “NKU”; • Should be initialized when declared • Can’t be changed
Number Type • All number values are represented internally as double-precision floating-point values • Whole numbers will display as integers • Can use exponent notation like Java: 1.23e45 • Arithmetic operations that result in an error (ex. /0) or produce a value not representable as a number return value “not a number”, displayed as NaN; use isNaN(…) function to check • Conversions: • parseInt(…) and parseFloat(…) functions turn strings into numbers • They convert string up to 1st non-valid character • Other implicit conversions (called coercions) • boolean to number gives 1 (true) or 0 (false) • null to number gives 0 • undefined gives NaN (not a number)
String Type • String literals = sequences of 0+ characters between pairs of either single or double quotes • No difference between ’ and ”, but end quote must match start quote • Can include escaped characters as in Java • E.g. \n, \”, \\, etc. • + sign is string concatenation operator (as in Java) if either side is a string • Conversions: • toString() method of Number object turns numbers into strings • Other implicit conversions • JS attempts to convert to a string the non-string operator in a string concatenation operation; ex. “August” + 1977
String Methods and Property • Belong to String object, but JS automatically converts primitive string values to wrapper objects → can be used through string primitive values directly • charAt( ): “George”.charAt(2) returns ‘o’ • Given integer argument, returns one character (as string) • Note character positions in strings begin at index 0 • indexOf( ):“George”.indexOf(‘r’) returns 3 • Given one search string, returns its index or -1 • substring( ): “George”.substring(2, 4) returns ‘org’ • Given start and end indexes, returns string • toLowerCase( ): “George”.toLowerCase() returns ‘george’ • toUpperCase( ) • Convert entire string • .length: “abcd”.length is 4
Name in Upper Case • http://www.nku.edu/~frank/csc301/Examples/formvalidation2.html
Boolean Type • Two values: true and false • These are reserved words • Note – not “true” or “false” (strings) • Conversions • When boolean converted to string, get “true” or “false” • Empty string is considered false, all others true • Number 0 is considered false, all others true • Undefined, NaN and null are considered false
Operators and Statements • Assignment statement uses = • Statements don’t require semicolon at end unless 2 statements on one line • However best practice is to terminate every line like Java;
Operators and Statements • The interpreter will insert the semicolon if missing at the end of a line and the statement seems to be complete; • Can be a problem: return x; • If a statement must be continued to a new line, make sure that the first line does not make a complete statement by itself.
Arithmetic Expressions • Basically the same as Java • Same numeric operators, including % • Same unary operators (+, -; prefix or postfix ++, --) • Same shortcut assignment operators (+=, *=, etc.) • Same rules of precedence and associativity • Same use of parentheses to create subexpression • All numeric operations are done in double-precision floating point division does NOT truncate integers: var i = 3 / 2; gives 1.5, not 1 as in Java • Operators (other than + operator) can be used with strings to get numeric results • i.e. var value = “3” * “4”; gives 12; coercion done by JS interpreter
Conditional Statements • Pretty much the same as in Java • if(control_expression) { … } • if(control_expression) {…} else {…} • Use..else if.. like Java • switch • Same syntax as Java; control expression and case labels can evaluate to number, string or boolean value; case labels can be of different types • Must use break to end execution after a match case • Best practice is to use Java-style indentation • Also has Java-style conditional expression operator ? : • Compound statement • = a sequence of statements delimited by braces • Not allowed in JS to create variables local to compound statement → such vars are visible either in whole document or function where are declared
Conditional (Relational) Operators • JS uses same comparison operators as Java • ==, <=, !=, etc. • If comparison mixes numbers and strings, strings are converted to numbers • i.e. 3.0 == “3.00” evaluates to true • Inswitch,case 3.0 andcase “3”are the same • In addition, uses === and !== • “Strictly equals” (or not) • In this case, no type conversion is done / allowed • Variables must match in type and value
Logical Operators • Same as Java • && and || and ! • As in Java, if 1st operand “tells the whole story”, the second isn’t checked = short circuit operators • Best practice is to put parentheses around each logical expression
Iteration • Basic loop statements same as in Java • while(...) { ... } • do {….} while(…) • for(init_expr; continue_expr; update_expr) {….}
Iteration • Also has for(variable in collection) {…} statement • in is a keyword here • variable is a var • Collection is a set of values • Arrays, for example (covered later) • Steps through the collection one item at a time, assigning each value to variable
Simple I/O • Window and Document • The Window object represents the browser window in which the document containing the script is being displayed • The Document object represents the document being displayed using DOM • The Window object is the default object for JavaScript, so properties and methods of the Window object may be used without qualifying with the object name; window & document are properties of the Window object
Simple I/O • To write to the current page, use write method of document • document.write(stringVar); • will write the string on current page and (if proper XHTML) display it • The code should be in body section executed & displayed when loaded • The output written should be XHTML code = tags + content demoWrite.html
Simple I/O • Three methods of built-in object Window are used to provide dialog box I/O • alert(string) • Puts up a dialog box containing the string & waits for dismissal • String is plain text, not XHTML! • confirm(string) • Displays dialog box with OK/CANCEL and returns true or false depending on button pressed demoAlert.html
Simple I/O • prompt(string, defaultAnswerString) • Collects a string of input from user, which returns as its value; w/ OK/CANCEL • Default is placed in text box • In all three cases, browser waits for a user response before JS interpreter continues demoPrompt.html
Your turn • Create XHTML + JavaScript Output: a table of the numbers from 5 to 10 and their squares and cubes, using tables. Solutions powers.html powers2.html powersA.html