FIT3084: JavaScript, Part 1
In the previous lecture:
In this lecture:
References
Sebasta, R. W. Programming the World Wide Web, 2009 / 5th edn, Pearson, chapt. 4
What is Javascript?
JavaScript is not Java! But it has (had) other names like: Livescript, JScript and ECMAScript.
There, now that's not so bad is it? You just asked your browser to execute some JavaScript.
<script language="Javascript"> |
<form> <input type="button" name="myButton" value="Panic Button" onClick="daisy()"> </form> |
JavaScript Syntax
JavaScript contains primitive types Number, String, Boolean, Undefined and Null, as well as predefined, corresponding wrapper object types of the same names.
The wrapper types contain a data-member holding a primitive value of their corresponding type, and methods for use on that type. Examples below...
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" |
String methods
Method | Parameters | Result | Example var str = "George"; |
charAt | A number | Return: character in the String object at the specified position | str.charAt(2) is 'o' |
indexOf | A single-character string | Return: the position in the String of the parameter | str.indexOf('r') is 3 |
substring | Two numbers | Return: the substring in the String object between the specified indices | str.substring(2,4) is 'org' |
toLowerCase | - | Convert any upper case characters in the string to lower case | str.toLowerCase() is 'george' |
toUpperCase | - | Convert any lower case characters in the string to upper case | str.toUpperCase() is 'GEORGE' |
2001 |
2001.0 | -2001.0 | 2.01E3 | 0x2A | 0743 |
+2001.0 Does not work! |
hexadecimal numbers preceded by a 0x digits from 0-F |
octal numbers preceded by a 0 digits from 0-7 |
The Math object contains methods for operating on Number objects, as well as some properties, e.g. Math.sin(x) or Math.round(x)
Keywords true and false
These are not the same as 1 and 0!
// This is a comment to the end of a line
/* This is a comment
which spans more
than one line */
Some very old browsers do not recognise the <script> tags and will reproduce their contents as text (i.e. the JavaScript code will be displayed in the browser window instead of being executed.
The XHTML validator will also struggle if the JavaScript contains recognisable tags in its output, sometimes causing validation errors.
To avoid these problems, encapsulate your JavaScript code in XHTML comments between an XHTML comment openeer <!-- and a JavaScript comment followed by the XHTML comment closer on its own line // -->
Like this...
<!--
JavaScript code
// -->
Type conversion may be implicit (coercion) or explicit. Most commonly these conversions are between Numbers and Strings.
If either operand of a + operator is a string, the other operator is implicitly converted to a string...
"HAL " + 9000 = "HAL 9000" |
Strings are automatically converted to numbers if you try to perform arithmetic with them...
"12" * 2 = 24 |
Strings containing numbers can be explicitly converted to Numbers and vice versa using constructors...
var number = Number(aString); var string = String(aNumber); |
Strings can be converted to numbers of specific bases also...
var string = number.toString(); // default is decimal var binaryString = number.toString(2); // base 2 |
Also see parseInt(), parseFloat(). These check a string parameter to see if its leading charcaters can be converted to an Integer or Float respectively.
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!
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); } |
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;
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 did not support C's switch( ) statement however this is now available.
Unlike in C, you can compare strings using the comparison operators.
if (name < "D")
{ alert("Your name comes before Dave's alphabetically"); }
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(); |
To make a new array...
var myArray = new Array(thing1, thing2, "thing3" thing4); // arrays can store multiple types
or
var myTenElementArray = new Array (10);
Also, JavaScript has some pre-defined arrays:
- browser history list
- current document list of hyper links
- list of frames in the current window
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]; } |
JavaScript is not truly object oriented although it is "object based" – JavaScript does not support class-based inheritance, it employs prototype-based inheritance (which we won't discuss).
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]; } |
JavaScript uses...
Form Validation (often using regular expressions...) |
Regular Expressions
JavaScript pattern matching is based on the regular expressions of Perl.
These are commonly used for form validation (checking for valid postal addresses, phone numbers, email addresses, postcodes etc.)
Simple pattern matching is achieved using the String search method.
var str = "ron ran rings around rod."; |
A period "." matches any character except a newline. To match a period, escape it with a backslash \
/r.n/ |
This matches ron, ran and rin. |
Characters between [ and ] indicate alternative matches.
/r[oa]n/ |
This matches ron and ran but not rin. |
A ^ character specified at the start of a class of characters inverts that set.
/r[^oa]n/ |
This matches rin (amongst other things) but not ran or ron. |
A - character indicates a range of characters for matches.
/[0-9]/ |
A digit |
/[A-Za-z]/ | An alphabetic character |
/[^A-Z]/ | Not a capital letter |
Whitespace can be detected.
/[ \r\t\n\f]/ | A whitespace character |
Patterns can be tested for a forced match at the beginning of a string with a leading ^ symbol, or the end of a string with a trailing $ symbol.
/^a/ | Matches a string that starts with an a |
/a$/ | Matches a string that ends with an a |
Other characters to research include * + ? { }
A Google Maps example
Interactive maps like Google maps - click & drag to pan, click controls to zoom |
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> |
©Copyright Alan Dorin 2009