Вы находитесь на странице: 1из 72

JavaScript Programming

Min Wu
mwu@itu.edu

ITU 2014

Topics
JavaScript has a programming language
Variables, data types, functions
OOP

Using JavaScript to access BOM and DOM


JavaScript event handling

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.

In-class final exam 40%


Open book
No electronic device

Attendance is required.

ITU 2014

JavaScript components
The Core (ECMAScript) Script language specification
DOM API to access and manipulate XML: add, remove,

replace, modify DOM nodes


BOM access and manipulate the browser window
No standard and each browser has its own implementation

ITU 2014

Source: Professional JavaScript for Web Developers

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

placeholder for a value


var operator to define/declare a variable and make it local to
the scope in which it is defined

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

function if the value is a function


Functions are objects with special properties

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

has not been defined at all

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

Any time an object is expected but is not available, null should

be used in its place. This helps to keep the paradigm of null as an


empty object pointer and further differentiates it from
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()

NaN: when an operation intended to return a number has failed (as

opposed to throwing an error)

A special numeric value


NaN is not equal to any value, including NaN
isNaN(): determine if a value is not a number or cannot be converted to a

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

Identically equal (===) and not identically equal (!==)


No conversion
ITU 2014

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

Primitive and reference values


Primitive value: the value is completely stored in one

memory location
5 primitive types: Undefined, Null, Boolean, Number, String

Reference value: the value stored in the variable is actually

just a pointer to another memory location where the object


is stored
Dynamic properties: properties and methods may be added,

changed, or deleted at any time


Primitive values can t have properties

ITU 2014

Assignment
When a primitive value is

assigned from one variable to


another, the value is created
and copied into the location
for the new variable
When a reference value is

assigned from one variable to


another, the pointer is copied
into the location for the new
variable
ITU 2014

Source: Professional JavaScript for Web Developers

Execution context
Global: the window object
Global variable and top-level function: dynamic properties

added to the window object


Local (function)
Scope chain: provide ordered access to all variables and

functions that an execution context has access to


Variable declaration: when a variable is declared using var, it is

automatically added to the most immediate context available.


No block-level scope

ITU 2014

The Object type


Create an instance
new operator with Object constructor
Object literal notation

Access property
Dot notation
Bracket notation: string containing the property name

ITU 2014

The Array type


Create an array
(new operator with) Array constructor: can pass size or items
Array literal notation

Length
Length can be dynamically updated

toString() method

ITU 2014

The Array related methods


Push(): add elements to the end; return new array length
Pop(): remove the last element; return the removed (last) element
Unshift(): add elements to the front; return new array length
Shift(): remove the first element; return the removed (first)

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

The Array manipulation methods


Concat()
Create and return a new copy of an array
Append the method arguments (elements or arrays)

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

The Date type


Store Date type as the number of milliseconds that have passed

since midnight on January 1, 1970 Universal Time Code (UTC)


new Date(): date object that is assigned the current data and time
new Date(milliseconds)
Date.parse(string_representation_of_date): return milliseconds
for the current time zone that can be used by new Date() or
NaN
month/date/year: 6/13/2012
month_name date, year May 25, 2012
<standard date string format as dates toString method>

Date.UTC(year, month(0, 11), day(1, 31), hours(0, 23),

minutes(0, 59), seconds(0, 59), milliseconds): return milliseconds


ITU for
2014 UTC

The Date type methods


Date formatting
toDateString(), toTimeString()
toLocalDateString(), toLocalTimeString()

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

The Function type


Functions are objects
Function names are pointers to function objects

Named functions are the same as anonymous functions assigned to

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

this object and function scope


this refers to the object that the function is operating on, or

this refers to the scope in which the function is being


executed
2 methods for function objects: apply(), call()
Execute function in a specific scope
apply(scope, [argument array]): function arguments are put into

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

JavaScript OOP prototype pattern


Each function is created with a special property called

prototype
Each instance created by the constructor has an internal
pointer __proto__

ITU 2014

Source: Professional JavaScript for Web Developers

Prototype pattern (II)


Property access: begin with the instance; if the property is

not found, continue up to the prototype


The property on the instance shadows the property with the
same name on the prototype
hasOwnProperty(): true only if the property exists on the
instance
In operator: true if the property is accessible by the object,
which means that the property is either on the instance or on
the prototype
For-in loop for all the accessible properties by an object
ITU 2014

Combination of constructor/prototype
pattern
Constructor pattern defines instance properties
Prototype pattern defines methods and shared properties

ITU 2014

Dynamic Prototype Pattern


Using prototype inside constructor
Only one definition block

ITU 2014

Inheritance
Two types of inheritance from OOP
Interface inheritance only the method signatures are inherited
Implementation inheritance actual methods are inherited

JavaScript only supports implementation inheritance since

JavaScript function does not have signature.

ITU 2014

Prototype chaining
Use prototype to inherit properties and methods between

two reference types


An instance from SuperType is assigned as the prototype
object of SubType: SubType.prototype = new SuperType();

ITU 2014

Source: Professional JavaScript for Web Developers

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

Browser Object Model (BOM)


Browser functionality that is independent from any web page

content
There is no standard BOM implementation or standard BOM
interfaces across different major browsers.

ITU 2014

Three main BOM objects


The window object
An instance of the browser
Global object that specifies the global scope

The location object window.location


Information about the document that is currently loaded
Supporting navigation functionality

The history object window.history


Users navigation history

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

Open windows (cont.)


Specs: a comma - delimited string of settings indicating

display information for the new window


Height, left, top, width position and size
Location, menubar, toolbar, status whether a browser

component should be displayed


Resizable
Scrollbars
Replace: whether the URL creates a new entry or replaces

the current entry in the history list

ITU 2014

Intervals and timeouts


var timer = setTimeout(function () {}, milliseconds);
clearTimeout(timer);
Function is triggered at a later time
var intervalId = setInterval(function () {}, milliseconds);

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

Result is true if OK is clicked


Result is false if Cancel is clicked

Var result = Prompt(): dialog for users input with OK and Cancel

buttons

Result is the value in the text box if OK is clicked.


Result is null if Cancel is clicked or the dialog is closed without

clicking OK.

Window.print() display browsers print dialog


Window.find() display browsers find dialog
ITU 2014

The location object


The location properties
Host
Hostname
Port
Href: full URL
Pathname
Protocol http: or https:
Search query string of the URL, starting with ?

ITU 2014

The location object (cont.)


Navigation
Location.assign(url) same as
Window.loaction = url
Location.href = url
Location.replace(url) the current page will not be in the

history stack
Location.reload(true) retrieve from the server again

ITU 2014

The history object


Each browser window/tab has its own history object.
History.go(number_of_steps)
-1: back
1: forward
2: forward 2 pages

History.back(), history.forward()
History.length the size of the history stack

ITU 2014

Document Object Model (DOM)


A hierarchy of nodes from HTML/XML document
12 node types
Node.ELEMENT_NODE (1)
Node.ATTRIBUTE_NODE (2)
Node.TEXT_NODE (3)
Node.DOCUMENT_NODE (9)

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)

<!--

To change this template, choose Tools |

comment node (8)

document type node (10)

element node (1)

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

nodes that are accessible by position/index


childNodes[i]

firstChild
lastChild
parentNode
nextSibling
previousSibling
ITU 2014

Source: Professional JavaScript for Web Developers

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

element in the document with idname


document.getElementsByTagName(tagname) // return
HTMLCollection object
document.getElementsByName(name) // return
HTMLCollection object
Special collections
Document.anchors
Document.forms

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

getAttribute(attrName) and setAttribute(attrName,

attrValue)

Work with custom attributes


ITU 2014

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)

newNode = oldNode.cloneNode([true]) // deep clone


newNode = oldNode.cloneNode(false) // shallow clone
ITU 2014

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

then flows upward towards the least specific node


(document)
Event capturing: the least specific node (document) receives
the event first, and the most specific node receive the event
last

ITU 2014

Source: Professional JavaScript


for Web Developers

Event handling
A function is called in response to an event
Naming convention
Events: click, load, mouseover
Event handlers: onclick, onload, onmouseover

HTML event handlers HTML attribute with the name of

the event handler


DOM level 0 event handlers DOM elements with event
handler properties
Remove event handler by setting the event handler properties

to null
ITU 2014

Event handling (cont.)


DOM level 2 event handlers addEventListener /

removeEventListener
Can specify whether to call the event handler during the

capture phase or during the bubbling phase


Can add multiple event handlers for a single DOM element

ITU 2014

Event object
When an event related to the DOM is fired, all of the

relevant information is gathered and stored on an object


called event.
event is a special variable for the event object in HTML event

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

followed by a mouseup event on the same element.


Event object properties
Coordinates: clientX, clientY, screenX, screenY
Modifier keys: shift, ctrl, alt, meta
Button: which mouse button is pressed/released (mousedown

and mouseup events only)

ITU 2014

Keyboard events
Keydown, keypress, keyup
A character key is pressed: keydown, keypress, (any changes

made to the text box,) and then keyup


A non-character key is pressed: keydown, and then keyup
Event object properties
KeyCode: for keydown and keyup events
CharCode: for keypress event only
Using String.fromCharCode(charCode) to covert the character

code to the actual character

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

event. That is, window.onload is triggered after


image.onload.
Resize related to the browser window
Focus, blur related to any DOM element
elem.focus() set elem in focus

Select, change, submit, reset related to form and its

included DOM elements


ITU 2014

Form-related events
Change event from
Input text field
Select widget
Checkbox
Etc.

Select event from


Input text field
Text area

ITU 2014

Mutation events
DOMSubtreeModified
DOMNodeInserted
DOMNodeRemoved
Can always add them to the document, and use

event.target.id to find out which element actually fired those


events

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

Вам также может понравиться