980 likes | 1.14k Views
JavaScript II: Into the Details. Marek Podgorny, EECS, Syracuse University, and CollabWorx. JavaScript Syntax. Basic Syntax. JavaScript syntax resembles Java and C Braces { } are used for grouping Use single or double quotes (equivalently) around string literals
E N D
JavaScript II: Into the Details Marek Podgorny, EECS, Syracuse University, and CollabWorx
Basic Syntax • JavaScript syntax resembles Java and C • Braces { } are used for grouping • Use single or double quotes (equivalently) around string literals • Escapes: \b \t \n \f \r \" \' \\ • Other literals: null, true, and false • JavaScript is case-sensitive while HTML is not (which sometimes leads to problems!) Fall 2002
Variables • Variables (identifiers) must begin with a letter, underscore, or dollar sign: var := [a-zA-Z_$][a-zA-Z0-9_$]* • Declare variables in var statements:var aNumber = 137;var aString = "1"; • JavaScript “entities” in HTML attributes:<IMG SRC="&{v1};" WIDTH="&{v2};">where v1 and v2 are JavaScript variables Fall 2002
Operators • Assignment operators: = += -= *= /= %= <<= >>= >>>= &= ^= |= • JavaScript supports the usual arithmetic operators, as well as: %++-- • Concatenation operator: + • Bit operators: & | ^ ~ << >> >>> • Relational operators: == > >= < <= != • Logical operators: && || ! Fall 2002
Expressions • Examples: sum += x; // sum = sum + x r -= n; q++; s = "temp" + 1; // assign "temp1" to s phi = (1 + Math.sqrt(5))/2; valid = (age > 21 && age <= 65); • An if-expression returns a value: p = ( k < 0 ) ? 1/y : y; Fall 2002
Reserved Words Fall 2002
Statements • JavaScript statements include: break, continue, do, for, function, if, return, switch, var, while, and with • Multiple statements on one line are separated by semicolons • Statement blocks are delimited by braces • Comments come in two flavors:/* any text including newlines */// comment terminated by newline Fall 2002
The if Statement • Assuming Boolean variable isWhite: if ( isWhite ) { document.bgColor = "pink"; isWhite = false; } else { document.bgColor = "white"; isWhite = true; } • The else block is optional, of course Fall 2002
The switch Statement • The switch statement is new is JS 1.2:switch ( fruit ) { case "oranges": price = 0.59; break; case "apples":price = 0.32; break; case "bananas": price = 0.48; break; default: price = null; } Fall 2002
The for Statement • A simple for-loop: // Compute x^k for k > 0: for (var y=1, i=0; i<k; i++) { y *= x; } • Here is another type of for-loop: for (var prop in object) { statements } Fall 2002
The while Statement • A more general looping structure: // Compute r = m % n for m,n > 0: var r = m; while ( r >= n ) { r -= n; } • break, labeled break, and continue are permitted in for and while loops • JavaScript supports recursion as well Fall 2002
The do…while Statement • A do…while loop tests its condition at the bottom of the loop:do {statements } while ( condition ); • In this case, the statements in the loop body are guaranteed to execute at least once Fall 2002
The with Statement with ( someObject ) {statements} • someObject is the default object used for any unqualified object references is statement scope:with ( Math ) {area = PI*r*r; // Math property PIx = r*cos(theta); // Math method cosy = r*sin(theta); // Math method sin} Fall 2002
Browser Objects Fall 2002
Window and Frame Objects • A Window object—the top-level JavaScript object—is the reflection of a <BODY> or <FRAMESET> tag • A browser window may be divided into sub-windows called frames • A Frame object—the reflection of a <FRAME> tag—“inherits” all of its properties and methods from the Window object Fall 2002
Window Properties • window and self are synonyms for the current window • top refers to the highest-level window in a hierarchy of frames • parent refers to the previous window or frame in a hierarchy of frames • A window may have a name:myWin = window.open(URL); Fall 2002
Window Properties (cont’d) • An analogy with the UNIX shell: Fall 2002
Frame Properties • A Frame object also has properties called window, self, and parent • The most important property of the Frame object is the frames[] array • Each <FRAME> tag automatically creates an entry in the frames[] array • Frames may also have names, as in<FRAME NAME="upperFrame"> Fall 2002
Frame Example <!-- File: index.html --> <HTML> <FRAMESET ROWS="90%,10%"> <FRAME SRC="skeleton.html" NAME="upperFrame"> <FRAME SRC="navigate.html" NAME="navigateFrame"> </FRAMESET> <NOFRAMES>...</NOFRAMES> </HTML> Fall 2002
Frame Example (cont’d) • <!-- File: skeleton.html --><HTML><FRAMESET ROWS="30%,70%"> <FRAME SRC="category.html” NAME="listFrame"> <FRAME SRC="titles.html” NAME="contentFrame"></FRAMESET></HTML> Fall 2002
Frame Example (cont’d) • Absolute references: top.navigateFrame top.upperFrame top.upperFrame.contentFrame top.upperFrame.listFrame • Relative references: parent.upperFrame parent.contentFrame parent.parent.navigateFrame In which documents are these references valid? Fall 2002
Frameset Documents • The <FRAMESET> and <BODY> tagsare mutually exclusive • No closing tag for <FRAME> is needed • A frameset document may contain a <SCRIPT> in its <HEAD> • Use <NOFRAMES> inside <FRAMESET>for frames-impaired browsers Fall 2002
Window and Frame Methods • Both Window and Frame objects have blur, focus, clearTimeout, and setTimeout methods • The Window object also has alert, close, confirm, open, and promptmethods. For example,var msg = "The alert() method\n";msg += " is handy for debugging."; window.alert( msg ); Fall 2002
Location Object • The Location object corresponds to the URL of the current document • To load a new document into the current window, use:window.location.href = "foo.html";or simplywindow.location = "foo.html"; • Location object properties: href, protocol, host, pathname, search Fall 2002
Document Object • There is one Document object (called document) per window or frame • The Document object has numerous sub-objects • Anchor, Applet, Embed, Area, Form, Image, Link, Layer • and property arrays • anchors[], applets[], embeds[], forms[], images[], links[], layers[] Fall 2002
Document Properties • A Document object has the following color properties: alinkColor, linkColor, vlinkColor, bgColor,and fgColor • Other Document properties include lastModifiedand URL:with ( document ) { writeln('<TT>', URL, '</TT><BR>'); writeln('Updated: ', lastModified); } Fall 2002
Document Properties (cont’d) • To list the properties of document:for ( var prop in document ) { with ( document ) { write( prop + " = " ); writeln( eval(prop), "<BR>"); } } • Recall that the with statement qualifies all object references within its scope Fall 2002
Document Methods • The write(…) and writeln(…) methods take a comma-separated list of string expressions • The open() and close() methods (not to be confused with window.open() and window.close()) open and close a document for writing, but these are seldom used explicitly Fall 2002
Form Objects • Every Form object is the reflection of an HTML <FORM> tag • The forms[] array may be indexed by integer or name (i.e., forms[0] or forms['myForm'] ) • A Form object has many subobjects, each corresponding to an HTML form element. These are reflected in the elements[] array Fall 2002
Form Properties • Form elements are reflected in the elements[] array. For example,document.forms[0].elements[1];is the second element of the first form • Most Form properties (action, encoding, method, and target) are read/write variables, that is, these properties may be modified on-the-fly Fall 2002
Form Methods • Invoking the submit() or reset() method on a Form object has the same effect as pressing the corresponding button • The event handlers onSubmit and onReset may be used to override the default submit and reset actions. Fall 2002
Image Objects • Images may be pre-loaded (they should be cached in the <HEAD>, especially if they are to be used in the <BODY>):var images = new Array( num ); for ( var i = 0; i < num; i++ ) {images[i] = new Image();images[i].src = "image"+ i +".gif"; } • This code loads files “image1.gif”, “image2.gif”, and so on Fall 2002
Image Animation • Now suppose we have the tag<IMG NAME=img>in the <BODY>. The following recursive method animates the cached images:var n = 0; function animate() { document.img.src = images[n].src;n = (n + 1) % images.length;id = setTimeout("animate()", 250); } Fall 2002
Layer Objects • Think of a Layer object (new in JS 1.2) as a dynamic document within a document • Each <LAYER> tag generates a Layer object and a corresponding element in the layers[] array • Layers have many methods and properties (most of which may be modified on-the-fly) • Note: Layers are not supported in MSIE Fall 2002
Built-in Arrays • JavaScript has numerous built-in arrays, each with its own length property: Plus the history array—the only one whose name does not end in “s”! Fall 2002
HTML-reflected Arrays Plus the elements array, whose parent is the Form object Fall 2002
Client-side String Methods • Client-side JavaScript defines more than a dozen String methods, including: Fall 2002
Navigator Objects • The Navigator object contains information about the browser • Two properties are appName and appVersion • Methods include javaEnabledand taintEnabled • All windows share the same Navigator object, which is truly global Fall 2002
MimeType Objects • The MimeType object is a subobject of the Navigator object • The mimeTypes[] array contains an entry for each MIME type supported by the browser • Properties of MimeType include description, type, and suffixes • The property enabledPluginrefers to a Plugin object Fall 2002
Plugin Objects • Like MimeType, the Plugin object is a subobject of the Navigator object • The plugins[] array contains an entry for each installed plugin • Each Plugin object is an array of MimeType objects. For example, navigator.plugins[0][0].typeis a MIME type supported by plugins[0] Fall 2002
More examples of constructors Fall 2002
User-defined Objects • Objects are defined with the function statement. The following Circle object, for example, has property r:function Circle( r ) { this.r = ( r > 0 ) ? r : 0; } • The this keyword permits this function to be used as a constructor:var c = new Circle( 2.0 ); var area = Math.PI * c.r * c.r; Fall 2002
User-defined Methods • Methods are defined as Function objects:function Circle( r ) { this.r = ( r > 0 ) ? r : 0; this.getRadius = new Function( "return this.r" ); this.setRadius = new Function( "r", "this.r = r" ); } • Note: The last argument of the Functionconstructor is implicitly the method body Fall 2002
Another Example • Here’s another example:function Car( make, model ) { this.make = make || ""; this.model = model || ""; this.color = null; this.setColor = new Function( "color", "this.color = color" );} • Instantiate a Car object with new:myCar = new Car( "Ford", "Explorer" );myCar.setColor( "red" ); Fall 2002
The prototypeProperty • Methods may be added after the fact:function Circle_area() { return Math.PI * this.r * this.r; }Circle.prototype.area = Circle_area; • Use the previous method as follows:var radius = 1/Math.sqrt( Math.PI ); var c = new Circle( radius ); var area = c.area(); Fall 2002
The prototypeProperty (cont’d) • We can add methods to built-in objects, too:// Does an array contain element x ?function contains( x ) { for (var i=0; i<this.length; i++) { if (this[i] == x) return true; } return false;} • Now add the method to the Arrayobject with the prototype property:Array.prototype.contains = contains; Fall 2002
Prototype-based Inheritance • Define the parent object:function Ellipse( r1, r2 ) { this.r1 = ( r1 > 0 ) ? r1 : 0; this.r2 = ( r2 > 0 ) ? r2 : 0; this.area = new Function( "return Math.PI * this.r1 * this.r2" ); } • Define the child object:function Circle( r ) { this.r = ( r > 0 ) ? r : 0; this.parent = Ellipse; this.parent( r, r ); }Circle.prototype = new Ellipse; Fall 2002
Back to Objects Fall 2002
The Global Object • The implicitly defined Global object is the top-level JavaScript object • It has two properties: NaN (Not-a-Number) and Infinity (but NN supports neither) • There are seven global functions: Fall 2002