FIT3084: JavaScript,
Part II
In the previous lecture:
- JavaScript is a client side programming language that may be embedded
within an HTML document.
- JavaScript allows for user interaction, dynamic generation of content,
form checking, and much more...
In this lecture:
References:
Same as the previous lecture:
- Flanagan, D. JavaScript: The Definitive Guide
2nd edn, O'Reilly & Associates, Inc.
- Stein, L.D. How To Set Up and Maintain a Web Site
2nd edn, Addison Wesley 1997, Chpt10.
- Goodman, D. Dynamic HTML: The Definitive Reference
O'Reilly & Associates, Inc.
- It is essential that one or more of these texts, or some other reference
(eg. the WWW) be consulted on this topic.
- This page is a summary only of a few important JavaScript language features
after Stein. It is not intended to be a comprehensive explanation of
JavaScript.
Strings
- "This is a string" and 'This is a string'
- 'T' 'h' "e" "s" "e" "are strings too!"
- There is no distinction between single characters and strings
- Single quotes are useful:
onClick = "confirm('Are you
sure you want to become a potato Dave?')" |
- You can escape a quotation mark using backslash:
quote = "\"Eat my shorts
HAL!\", muttered Dave." |
- \n linefeed (UNIX newline), \r carriage return (Macintosh
newline) \t (tab)
- Strings may be concatenated using the + operator.
- The escape() and unescape() global functions convert strings
to URL encoded versions and vica-versa. For example:
var s = escape("hello dave");
// s now has the value: "hello%20dave"
|
Numbers
- 2001
- 2001.0
- -2001.0
- +2001.0 Does not work!
- 2.01E3
- 0x2A (hexadecimal numbers preceded by a 0x, digits from 0-F)
- 0743 (octal numbers preceded by a 0, digits from 0-7)
Booleans
- Keywords true and false
- These are not the same as 1 and 0!
Comments
- // This is a comment to the end of a line
- /* This is a comment
which spans more
than one line */
Type Conversion
- JavaScript has automatic type conversion
- eval (string) forces conversion of a string to a numeric value.
var aString = "2001";
var aNumber = eval(aString);
|
- parseInt (string, [radix]) returns an integer value up to the
first non-numeric character in the string. Base 10 is assumed if no radix
is specified.
- parseFloat (string) returns a floating point value or NaN
(not a number) if the string contains any non-numeric characters.
- isNaN(expression) returns true or false if number
is NaN. (Windo$ implementation of parseFloat() may return 0 instead
of NaN!)
- isFinite(expression) returns true or false if the
result of expression is anything within the range of Number.MIN_VALUE
and Number.MAX_VALUE
- JavaScript is weakly typed hence the statements...
myVariable = "Dave";
myVariable = 2001; |
...work just fine one after another even though one assigns myVariable
to a string and the other to a number!
- Strings are automatically converted to numbers if you try to perform
arithmetic with them. (& vice versa)
- Variable names must be alphanumeric characters starting with a letter
or underscore. (Case is significant)
- Variables do not need to be declared before use but it is important
to declare local variables in a function to avoid overwriting global variables
of the same name!
aVariable = "HAL";
function eliminateDave () // Function to keep HAL happy
{
var aVariable = "Dave";
eliminate(aVariable);
} |
Operators & Expressions
The following operators and expressions are valid in JavaScript, just
as they are in the C programming language.
- x = a + (b - 2001 * (c % 2)) / 10.1
- x++; x--; y = ++x; y = x--; x += 2001 etc.
- (x && y); (x || y); y = !x;
Comparisons & Conditional Statements
The following are valid in JavaScript, just as they are in the C programming
language.
- if (x > 2001){ ... }
else if (x < 2001){ ... }
else { ... }
- result = (x > 2001) ? ( ... ) : ( ... );
- x >= y; x <= y; x > y; x < y; x ==
y; x != y
- Early versions of JavaScipt do not support C's switch() statement.
- Unlike in C, you can compare strings using the comparison operators.
if (name < "D")
{ alert("Your name comes before Dave's alphabetically"); }
Loops
The following are valid in JavaScript, just as they are in the C programming
language.
- var year=0;
while (year < 2001) { ...; year++; }
- for (year=0; year < 2001; year++) { ... }
- break; continue;
- Also see for ... in loops.
- JavaScript function definitions are made using the function keyword.
- JavaScript function definitions do not include the return type.
- Sample function definitions
function blah() { ... }
function bloo(myVar) { ... }
function blod(myVar1, myVar2) { return myVar1 + myVar2; }
|
- Functions are called using C syntax:
machineName = blod("Hal",
"9000"); |
- Remember to declare local variables to avoid
over-writing globals!
- Functions can be assigned to variables. (The variable is a reference
to the function)
function eliminateHAL() {
... }
function singToHAL() { ... }
function doSomethingDave()
{
var action;
if (misbehave(HAL)) { action = eliminateHAL; }
else { action = singToHAL; }
return action;
}
thingToDo = doSomethingDave();
thingToDo();
|
Arrays
- JavaScript has some pre-defined arrays:
- browser history list
- current document list of hyper links
- list of frames in the current window
- You cannot (strictly speaking) create your own JavaScript arrays
- Array indices begin at 0.
- Arrays are indexed using square brackets [ and ].
- Arrays have a read only length property which holds the size
of the array.
- Sample array access:
for (var i = 0; i < document.links.length;
i++)
{ link = document.links[i]; } |
Objects
- JavaScript is not truly object oriented.
- JavaScript "objects" contain data parts (properties) and functions (methods).
-
Creating a JavaScript Object
Create a constructor function with the same name as the object
type.
The constructor can have any number of arguments.
Constructors return no result.
Constructors are responsible for defining the data and method members
of an object.
function spaceShip(name,
captainName, numberOfEngines)
{
this.shipName = name;
this.pilotName = captainName;
this.engines = numberOfEngines;
}
|
Remember that variables can be references to functions
too!
Call the new operator to create instances of the object.
discovery = new spaceShip("Discovery",
"Dave", 1);
enterprise = new spaceShip("Enterprise", "Kirk", 3);
|
-
Accessing Object Members
Access works just like access to a C struct's fields.
discovery.engines = 0; //
Discovery's engine is not operational
enterprise.shipName = "klingonStarshipOne"; // Klingons hijack the
Enterprise
|
- JavaScript objects are really just arrays indexed by strings (rather
than integers).
- A special for ... in loop runs through the properties of an object
in the order they were created.
var prop; for (prop in discovery)
{ thePropHolder = discovery[prop]; } |
Some Web based Information and JavaScript applications:
Lloyd's JavaScript
reference.
Mozilla JavaScript
reference.
Firebug Javascript debugger that works with Mozilla Firefox.
AJAX (Asynchronous JavaScript and XML) for creating web applications where small amounts of data can be retrieved by a client (from the server) without requiring full page downloads.
A Google Maps example
JavaScript source utilises Google's API for its map software to display the above map:
<script src="http://maps.google.com/maps?file=api&v=2&key=SiteSpecificCode" type="text/javascript">
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-37.91270348039777, 145.1369800497491), 15);
map.setMapType(G_SATELLITE_MAP);
map.openInfoWindow(map.getCenter(), document.createTextNode("Monash University -- here we are!"));
var mapControl = new GSmallZoomControl();
map.addControl(mapControl);
}
</script> |
This lecture's key point(s):
- JavaScript is a full featured programming language, with a syntax reminiscent
of C.
- JavaScript is, however, weakly typed and has limited support for Object-Oriented
programming.
Courseware | Lecture notes
©Copyright
Alan Dorin 2008