Chapter06 JavaScript
Chapter06 JavaScript
Introduction
JavaScript is a scripting language most often used
for client-side web development.
EditGrid
http://www.editgrid.com/
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
Inside your_source_file.js
</html>
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
First character cannot be a digit
Case-sensitive
Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
</script></head>
Local variable is declared using the keyword 'var'.
Dynamic binding – a variable can hold any type of value
If a variable is used without being declared, the variable is created
automatically.
If you misspell a variable name, program will still run (but works incorrectly)
Data Types
Primitive data types
Number: integer & floating-point numbers
Boolean: true or false
String: a sequence of alphanumeric characters
Post/pre increment/decrement
++, --
Comparison operators
==, !=, >, >=, <, <=
===, !== (Strictly equals and strictly not equals)
i.e., Type and value of operand must match / must not match
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true
|| – Logical OR
OP1 || OP2
If OP1 is true, expression evaluates to the value of OP1.
Otherwise the expression evaluates to the value of
OP2.
var tmp1 = null && 1000; // tmp1 is null
Assignment operators
=, +=, -=, *=, /=, %=
Bitwise operators
&, |, ^, >>, <<, >>>
Conditional Statements
“if” statement
“if … else” statement
"? :" ternary conditional statement
“switch” statement
alert(keys);
// Show "prop1 prop2 pro3 "
alert(values);
// Show "123 456 true "
Example: Using for … in loop with object
Functions (Return Values)
// A function can return value of any type using the
// keyword "return".
foo(1); // returns 0
foo("abc"); // returns "zero"
foo(); // returns undefined
Variable Arguments
// "arguments" is a local variable (an array) available
// in every function
// You can either access the arguments through parameters
// or through the "arguments" array.
function sum ()
{
var s = 0;
for (var i = 0; i < arguments.length; i++)
s += arguments[i];
return s;
}
isFinite(x)
Determines if a number is finite
isNaN(x)
Determines whether a value is “Not a
Number”
Built-In Functions
parseInt(s)
parseInt(s, radix)
Converts string literals to integers
Parses up to any character that is not part of a valid integer
parseInt("3 chances") // returns 3
parseInt(" 5 alive") // returns 5
parseInt("How are you") // returns NaN
parseInt("17", 8) // returns 15
parseFloat(s)
Finds a floating-point value at the beginning of a string.
parseFloat("3e-1 xyz") // returns 0.3
parseFloat("13.5 abc") // returns 13.5
Creating Objects
JavaScript is not an OOP language.
"prototype" is the closest thing to "class" in
JavaScript.
alert(triangle.p1.y); // Show 3
Object Constructor and prototyping
function Person(fname, lname) {
// Define and initialize fields
this.firstName = fname;
this.lastName = lname;
// Define a method
this.sayHi = function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text
"CUHK Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>