View
53
Download
0
Category
Preview:
DESCRIPTION
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: - PowerPoint PPT Presentation
Citation preview
1
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 JavaScriptBUT 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 existSupported by Firefox, Internet Explorer etc.
2
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 pagesValidate formsModify pages on the flyRead/write cookiesDoes not support however file operations, db access, networking
3
Implementation JS is an interpreted language
Not compiled into machine or byte codeSource code is read when it is to be run, interpreted and executed
Interpreters are part of the browserBrowsers implement different featuresBrowsers may implement the same feature differentlyVariations are greatest among older versions of browsers
JS vs. JavaJS has a different object model from Java:
based on object-prototypes, not on classes; objects are dynamic, their properties & methods can change during
executionJavaScript is not strongly typed:
vars need not be declared & are dynamically typed (=assigned values of different types)
4
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>
5
XHTML/JavaScript – Script Tag
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
6
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
7
Location of JavaScript Code
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
comments8
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 validatorsEnd 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>
9
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>
10
JavaScript Language JS is an object-based language, not an object-
oriented languageHas objects (that encapsulate both data and processing) and
references, like JavaNo general class definitionsDoes not have true, class-based, inheritance; polymorphism;
and subtypingHas 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-fly11
Define names just like in JavaBest practice - start with a letter, not special
characterUse CamelCase notation = write compound
words in which the words are joined without spaces and are capitalized within the compound
12
JavaScript Variable Names
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
13
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
14
JavaScript Variables
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 matters15
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
16
JavaScript Variable Types
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
17
Other JS Primitive Types Can find the current data type of a variable via
typeof operator(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”
18
Declared with the const keyword
const RETIREMENT_AGE = 65; const SCHOOL = “NKU”;
Should be initialized when declared Can’t be changed
19
JS Constants
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)
20
Number Type
String literals = sequences of 0+ characters between pairs of either single or double quotesNo 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 stringsOther implicit conversions
○ JS attempts to convert to a string the non-string operator in a string concatenation operation; ex. “August” + 1977
21
String Type
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 3Given 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
22
String Methods and Property
Name in Upper Case
http://www.nku.edu/~frank/csc301/Examples/formvalidation2.html
23
Two values: true and falseThese are reserved wordsNote – not “true” or “false” (strings)
ConversionsWhen boolean converted to string, get “true”
or “false”Empty string is considered false, all others
trueNumber 0 is considered false, all others trueUndefined, NaN and null are considered false
24
Boolean Type
Assignment statement uses = Statements don’t require semicolon at end
unless 2 statements on one lineHowever best practice is to terminate every line
like Java;
25
Operators and Statements
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.
26
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
27
Arithmetic Expressions
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
28
Conditional Statements
JS uses same comparison operators as Java==, <=, !=, etc.If comparison mixes numbers and strings, strings
are converted to numbersi.e. 3.0 == “3.00” evaluates to trueIn switch, case 3.0 and case “3” are the same
In addition, uses === and !==“Strictly equals” (or not)In this case, no type conversion is done / allowedVariables must match in type and value
29
Conditional (Relational) 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
30
Logical Operators
Basic loop statements same as in Javawhile(...) { ... }do {….} while(…)for(init_expr; continue_expr; update_expr) {….}
31
Iteration
Iteration Also has for(variable in collection) {…}
statementin is a keyword herevariable is a varCollection is a set of values
○ Arrays, for example (covered later)○ Steps through the collection one item at a
time, assigning each value to variable
32
Window and DocumentThe Window object represents the browser window in which the
document containing the script is being displayedThe Document object represents the document being displayed
using DOMThe 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
33
Simple I/O
Simple I/O
To write to the current page, use write method of documentdocument.write(stringVar); will write the string on current page and (if proper
XHTML) display itThe code should be in body section executed &
displayed when loadedThe output written should be XHTML code = tags +
content
34
demoWrite.html
Three methods of built-in object Window are used to provide dialog box I/Oalert(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
35
Simple I/O
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
36
demoPrompt.html
Create XHTML + JavaScript Output: a table of the numbers from 5 to 10 and their squares and cubes, using tables.
Solutionspowers.html
powers2.html
powersA.html37
Your turn
Recommended