Академический Документы
Профессиональный Документы
Культура Документы
Min Wu
mwu@itu.edu
ITU 2014
Topics
JavaScript has a programming language
Variables, data types, functions
OOP
ITU 2014
Recommended book
Professional JavaScript for Web Developers (3rd edition)
http://www.amazon.com/Professional-JavaScript-
Developers-NicholasZakas/dp/1118026691/ref=sr_1_8?ie=UTF8&qid=13464
88523&sr=8-8&keywords=javascript+programming
ITU 2014
Tools
XAMPP Server-side support
NetBeans IDE PHP bundle
Firefox
Firebug Firefox extension for JavaScript debugging
ITU 2014
Grading policy
In-class coding quizzes 60%
Bring your laptop all the time
Do not plagiarism. Identical code means F grade.
Attendance is required.
ITU 2014
JavaScript components
The Core (ECMAScript) Script language specification
DOM API to access and manipulate XML: add, remove,
ITU 2014
JavaScript in HTML
<script> element
Type attribute: required. text/javascript
Src attribute: optional. External JS file that contains code to be
executed
Put the script code in <head>
Put the script code at the end of <body>
Inline code vs. external file
Code reuse
Maintainability
Caching
Obtrusive JavaScript
ITU 2014
JavaScript basics
Case sensitive
Identifier vs. reserved words
Statements terminated by a semicolon
Loosely-typed variable
A variable can hold any type of data and is simply a named
ITU 2014
Data types
Undefined
Null
Boolean
Number
String
Object
Unsorted list of name-value pairs
There is no way to define your own data type in ECMAScript
Array
Function
ITU 2014
Typeof operator
undefined if the value is undefined
boolean if the value is a Boolean
string if the value is a string
number if the value is a number
object if the value is an object or null
ITU 2014
Undefined type
Only one value: undefined
When a variable is declared using var but not initialized
Variable containing the value of undefined vs. variable that
ITU 2014
Null type
Only one value: null
Null value is an empty object pointer the variable will later
hold an object
Undefined vs. null
Never explicitly set the value of a variable to undefined
ITU 2014
Boolean type
Two literal values: true and false
Boolean( ) casting function
false, hello true
0 false, NaN false, 10 true, Infinity true
new Object() true, any object true
null false
undefined false
ITU 2014
Number type
Both integers and floating-point values
Integers
base 10, 8, 16
All the integers are signed in ECMAScript
Range
Number.MIN_VALUE, Number.MAX_VALUE
Infinity (Number.POSITIVE_INFINITY), -Infinity
(Number.NEGATIVE_INFINITY)
isFinite()
number
ITU 2014
Number conversions
Number()
true 1, false 0
null 0
undefined NaN
0, hello NaN
parseInt(string [, radix])
NaN
parseFloat(string)
ITU 2014
String type
Double quotes or single quotes
string.length property
Strings are immutable in ECMAScript
ITU 2014
String conversions
String():
null null
undefined undefined
obj.toString():
obj cannot be null or undefined
Optional radix for num.toString()
ITU 2014
Equality
Equal (==) and not equal (!=)
If an operand is Boolean, convert it into the numeric value
If an operand is string and the other is a number, convert the string
into a number
If an operand is an object, first call valueOf() and then toString()
For example:
55 == 55 // true
null == undefined // true
null == 0 // false
undefined == 0 // false
NaN == NaN // false
Functions
function functionName(arg0, arg1,...,argN) {
statements
}
return statement
return; // return a undefined value
Function arguments
arguments.length
arguments[0],
All arguments are passed by value
No overloading
Functions in ECMAScript do not have signatures
The last function definition counts if functions have the same name
ITU 2014
memory location
5 primitive types: Undefined, Null, Boolean, Number, String
ITU 2014
Assignment
When a primitive value is
Execution context
Global: the window object
Global variable and top-level function: dynamic properties
ITU 2014
Access property
Dot notation
Bracket notation: string containing the property name
ITU 2014
Length
Length can be dynamically updated
toString() method
ITU 2014
element
Stack: last-in-first-out (LIFO) - push and pop
Queue: first-in-first-out (FIFO) push and shift
Reverse()
Sort()
Default: ascending order; comparing the string value of the array
elements
Sort with comparison function
ITU 2014
Slice(starting_index, stopping_index)
Create and return a new array that contains a section of the
original array
Stopping index is optional
Element at the stopping index is not included
Splice(starting_index, how_many, element1, , elementN)
Deletion: no element included in the method argument
Insertion: how_many=0
Replacement
ITU 2014
Date/time components
getFullYear, setFullYear, getUTCFullYear, setUTCFullYear
getMonth, setMonth, getUTCMonth, setUTCMonth
getDate, setDate, getUTCDate, setUTCDate (day of month)
getDay, getUTCDay (day of week)
getHours, setHours, getUTCHours, setUTCHours; Minutes;
Seconds; Milliseconds
getTimezoneOffset
ITU 2014
named variables
No overloading (no two functions with the same name)
Function declaration can be after function execution; function
expression has to be before function execution
Function declaration is always evaluated before function
expression, does not matter where they appear in the code.
function foo() { return hello;} // function declaration
var foo = function() { return world;}; // function expression
foo(); // world
ITU 2014
Function as values
Function can be assigned to a variable
Function can be passed to another function as argument
Function can be returned from another function as return
value
ITU 2014
Function properties
Arguments
Arguments.callee
Length
The number of arguments that the function expects
ITU 2014
an array
call(scope, arg1, , argN): function arguments are listed after
the scope
ITU 2014
JavaScript OOP
Create a custom object
var person = new Object();
Issue: duplicated code
Factory pattern
Using a create function
Issue: no object identification
Constructor pattern
Using constructor a normal function, but called by the new
operator
Using global function to avoid unique function object for
individual objects
Issue: create clutter in the global scope by introducing a
function that are used only in relation to an object
ITU 2014
prototype
Each instance created by the constructor has an internal
pointer __proto__
ITU 2014
Combination of constructor/prototype
pattern
Constructor pattern defines instance properties
Prototype pattern defines methods and shared properties
ITU 2014
ITU 2014
Inheritance
Two types of inheritance from OOP
Interface inheritance only the method signatures are inherited
Implementation inheritance actual methods are inherited
ITU 2014
Prototype chaining
Use prototype to inherit properties and methods between
ITU 2014
Constructor stealing
Call SuperType constructor from within SubType
constructor:
function SubType() {
SuperType.call(this);
}
No inheritance. No prototype chaining
The result is that each SubType instance has (steals) its own
copy of the properties from SuperType
ITU 2014
Combination inheritance
Prototype chaining + constructor stealing
Prototype chaining to inherit the properties and methods on
the prototype
Constructor stealing to inherit the instance properties
Most frequently used inheritance pattern in JavaScript
ITU 2014
Private variables
All object properties in JavaScript are public
Create private variables for reference types
Define all private variables inside the constructor
Define public methods to access the private members
ITU 2014
content
There is no standard BOM implementation or standard BOM
interfaces across different major browsers.
ITU 2014
ITU 2014
Opening windows
window.open(url, target, specs, replace)
Url
If no url, a new window with about:blank
Target
_blank: new window/tab (default behavior)
When no specs, a new tab is open
When specs is specified, a new window is open
_self : the current window is reloaded
name: a name of a window
window.open(url1, myWin);
window.open(url2. myWin); // open another url in the same
window/tab
ITU 2014
ITU 2014
clearInterval(intervalId);
Function is triggered repeatedly
ITU 2014
System dialogs
Alert(): message box without controls
Var result = Confirm(): confirmation dialog with OK and Cancel
buttons
Var result = Prompt(): dialog for users input with OK and Cancel
buttons
clicking OK.
ITU 2014
history stack
Location.reload(true) retrieve from the server again
ITU 2014
History.back(), history.forward()
History.length the size of the history stack
ITU 2014
ITU 2014
Node types
Node.ELEMENT_NODE (1)
ATTRIBUTE_NODE (2)
TEXT_NODE (3)
CDATA_SECTION_NODE (4)
ENTITY_REFERENCE_NODE (5)
ENTITY_NODE (6)
PROCESSING_INSTRUCTION_NODE (7)
COMMENT_NODE (8)
DOCUMENT_NODE (9)
DOCUMENT_TYPE_NODE (10)
DOCUMENT_FREGMENT_NODE (11)
NOTATION_NODE (12)
ITU 2014
document (9)
<!--
ITU 2014
Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
</head>
<body>
</body>
</html>
Node relationship
childNodes: a NodeList that stores an ordered list of the child
firstChild
lastChild
parentNode
nextSibling
previousSibling
ITU 2014
Document node
nodeType: 9
nodeName: #document
nodeValue: null
parentNode: null
document.body // reference to the <body> element
document.documentElement // reference to the <html>
element
document.title
document.URL
document.domain
ITU document.referrer
2014
Locating elements
document.getElementById(idname) // return the first
Document.images
Document.links
ITU 2014
Element node
nodeType: 1
nodeName: tag name
nodeValue: null
Standard attributes
Id: element.id
Class: element.className
Title tooltip: element.title
attrValue)
Text node
nodeType: 3
nodeName: #text
nodeValue: the text contained in the node
No child nodes
ITU 2014
Manipulating nodes
pNode.appendChild(newChild)
pNode.insertBefore(newChild, someChild)
pNode.replaceChild(newChild, oldChild)
pNode.removeChild(removedChild)
newENode = document.createElement(tagName)
newTNode = document.createTextNode(content)
newNode.setAttribute(attr_name, attr_value)
Attribute node
nodeType: 2
nodeName: attribute name
nodeValue: attribute value
parentNode: null
element.getAttributeNode(attrName)
element.setAttributeNode(attrNode)
ITU 2014
Event flow
The order in which events are received on the page
Event bubbling: event starts at the most specific element and
ITU 2014
Event handling
A function is called in response to an event
Naming convention
Events: click, load, mouseover
Event handlers: onclick, onload, onmouseover
to null
ITU 2014
removeEventListener
Can specify whether to call the event handler during the
ITU 2014
Event object
When an event related to the DOM is fired, all of the
handler
Properties: type, target, currentTarget, eventPhase
Methods: preventDefault(), stopPropagation()
ITU 2014
Mouse events
Click, dblclick, mousedown, mouseup, mouseout,
mouseover, mousemove
click event can only be fired if a mousedown event is fired and
ITU 2014
Keyboard events
Keydown, keypress, keyup
A character key is pressed: keydown, keypress, (any changes
ITU 2014
HTML events
Load, unload related to web pages
Resize related to the browser window
Focus, blur related to any DOM element
ITU 2014
HTML events
Load, unload related to web pages
Image can fire load event too.
Image load event is fired before the window load
Form-related events
Change event from
Input text field
Select widget
Checkbox
Etc.
ITU 2014
Mutation events
DOMSubtreeModified
DOMNodeInserted
DOMNodeRemoved
Can always add them to the document, and use
ITU 2014
Mutation events
Events fired when the DOM tree structure has changed
DOMSubtreeModified
DOMNodeInserted
DOMNodeRemoved
Use event.target.id to find out which element actually fired
those events
Events fired when the DOM node content has changed
DOMAttrModified
DOMCharacterDataModified
ITU 2014