The document provides an overview and agenda for a JavaScript bootcamp presented by Alexei White of Nitobi. The bootcamp will cover JavaScript basics like lexical structure, data types, objects, and arrays. It will also cover more advanced topics like debugging, DOM manipulation, events, and Ajax. The document includes the schedule, which is divided into three parts that progress from basics to advanced concepts. It also lists recommendations for integrated development environments (IDEs) on both Windows and Mac platforms.
2. A bit about me
-Development:
-Ruby/Rails, PHP, Coldfusion, Some
ASP.NET, C++ back in the day, Turbo
Pascal, etc, etc
-Design
-Enterprise Ajax
-Recent Projects:
-CompleteUI Component Suite
-Nintendo
-RobotReplay
-SayZu
3. About Nitobi
• Rich Internet Application
development.
• Off-the-shelf Ajax UI
components
• Cross Platform
•Java
•ASP.NET
•PHP
•Coldfusion
•Classic ASP
•Ruby on Rails
4. • Develop practical
Bootcamp Goals understanding of ECMAScript
• Actual coding
• Not too deep, not too shallow
• Remove mystery behind Rich
Internet Applications
• Expose the trouble spots
12. The impact of Browsers
• Sandbox implementation errors
• Minor implementation differences
– JavaScript
– Cascading Style Sheets
– Layout
– Supported media types
13. What Can you do in JavaScript?
• Draw boxes, images, and text
• Open and close windows
• Animate on-screen contents
• Modify the document
• Communicate with the server
• Talk to Java, Flash, Silverlight
• Snoop on the user.. record what they do.
• Read the mouse/keyboard
14. What it can’t do (1/2)
• Can’t open files
• Write to the file system
y Sa ndbox”
“Securit
• Talk directly to hardware
• Read freely from memory
• Perform general networking
– open a socket etc
• Do Ajax across domains
15. What it can’t do (2/2)
• Can’t close windows willy-nilly
• Hide the destination of links
• Open windows that are too small
• Set the value of FileUpload fields
• Rotate graphics
• Make sound
17. Lexical Structure
• All Unicode, all the time
– UTF-16 can represent most languages
– String operators respect encoding
• Case Sensitive (Most of the time)
>>> var A = 1; var a = 0; var a = 0;
>>> var a = 2; WHILE(a <= 2) { while (a <= 2)
>>> a a+=1; {
2 }; a+=1;
>>> A };
1
18. Lexical Structure
• Whitespace ignored
var a = 2;
if (a == 2)
console.log('yep');
console.log('Carrying on');
var a = 2; if (a == 2) console.log('yep'); console.log('Carrying on');
• Optional semicolons
a = 3 return But you probably meant
b = 4 true;
return true;
Will be executed as Will be executed as
a = 3; return;
b = 4; true;
19. JavaScript Gotcha’s
Whitespace & Semicolons
• Filesizes reduced by removing whitespace
• Missing semicolons can cause JS errors
a = 3
b = 4
Will be become y
No Work
a = 3 b = 4
20. Lexical Structure
• Comments
// This is a single-line comment.
/* This is also a comment */ // here is another comment
/*
* This is a multiline comment
*
*/
• Literals
12 // The number 12
“hello world” // A string of text
‘hey now’ // Another string
true // A boolean value
/javascript/gi // A “regular expression” literal
Null // Absense of an object
21. Lexical Structure
• Object Literals
{ name: “Alexei”, weight: 160 } // An object initializer
[23,345,12,341,2] // An array initializer
[{a:2},{a:56,name:’Buck’},{c:65}] // An array of objects..
• Identifiers (Variables)
a 34fg
my_variable_name .vgf
v382
_something
$
$fgj
22. Lexical Structure
• Reserved Words • Reserved & Special
break null abstract int
case return boolean interface
catch switch byte long
continue this char native
default throw class package
A biggie
delete true const private
do try debugger protected
else typeof double public
false var enum short
finally void export static
for while extends super
function with final synchronized
if float throws
in goto transient
instanceof implements volatile
new import
23. Lexical Structure
• Words to avoid
arguments NaN
ie Array Number
A bigg Boolean Object
console parseFloat
Date parseInt
decodeURI RangeError
decodeURIComponent ReferenceError
encodeURI RegExp
Error String
escape SyntaxError
eval TypeError
EvalError undefined
Function unescape
Infinity URIError
isFinite
isNan
Math
26. Datatypes – Useful Information
• Numbers
– All floating point
– 64 bit (huge)
• (+/-) 1.7976931348623157x10308
• Small: 1.474334E-32
– Hexadecimal Literals
• 0xff , 0xCAFE911
– Numeric Constants
• Infinity, NaN, Number.MAX_VALUE,
Number.NEGATIVE_INFINITY
27. Datatypes – Useful Information
• Strings
– Modern ECMAScript implementations support Unicode
– Escape sequences:
• ‘You’re always saying what can’t be done’
• u for unicode (eg: u03c0 for π)
– Concatenation
• Myname = first_name + ‘ danger ‘ + last_name;
– Strings are objects
• Myname.length, Myname.indexOf()
– Convert numbers to strings
• Msg = 100 + ‘’; Msg = String(100); Msg = 100.toString();
– Strings to Numbers
• Myval = parseInt(“3 people”) // 3
28. Datatypes – Useful Information
• Boolean Values
– Often the result of comparisons (a == 4)
– Used in control structures:
if (a == 4)
b = b + 1;
else
b = b – 1;
– Type conversions are often automatic
• Numeric : true == 1, false == 0
c = true + true // 2
d = true + ‘’ // ‘true’
– Type conversion is easy
var x = Boolean(1); // true
a = 1;
var y = !!a; // true
29. Datatypes – functions
function square(x) { // function is called square, expects 1 argument
return x*x; // the function squares its arg and returns result
} // function ends here
• Functions can be stored in variables,
arrays, etc.
• Can define lambda or anonymous
functions
function square(x) {
return x*x; var square = function(x){ return x*x; }
} =
30. Datatypes – objects
• JavaScript has built-in objects
document.forms window.innerWidth
document.images window.scrollY
• Objects are associative arrays
document.forms document[“forms”]
document.images = document[“images”]
• Invoked using new keyword
var a = new Object(); a.x = 1.1; a.y = 344;
var now = new Date();
var pattern = new RegExp(“sjavas”, “i”)
32. Datatypes – objects
• Object conversion: Does an object exist?
if (myObj) {
// Do something
}
• Objects as strings
a = {b:34,t:4}
b = a + “” // “[object Object]”
33. Datatypes - arrays
• A collection of values, like an object
• Can contain any type of JS data
var a = new Array(1.1, “something”, true, {x:43,y:34});
var b = new Array();
b[0] = 1.1;
b[1] = “something”;
b[2] = true;
b[3] = {x:43,y:34};
var c = new Array(20);
34. Datatypes - arrays
• Array literals
var a = [1.2, “something”, true, {x:33,y:34}];
• Sparse arrays
var a = [1,,,,5];
• Array length
a.length
• Searching
var array = [2, 5, 9];
var index = array.indexOf(5); // index is 1
index = array.indexOf(7); // index is -1
35. Datatypes – null & undefined
• null
– Indicates no value
– No object
– Converts to false in Boolean context (if (null))
• undefined
– Not null
– Used when a variable is declared but has no value
• Comparing the two
– null == undefined
– null !== undefined
36. Datatypes - dates
• Not a fundamental type, but a class of object
• Easily use local or GMT time.
var now = new Date(); // create an object holding current
// date and time
var xmas = new Date(2007,11,25);
• Date math, and type conversion
xmas.setFullYear(xmas.getFullYear() + 1); // Next christmas
var weekday = xmas.getDay(); // Day of week
console.log(“Today is: “ + now.toLocaleString());
// Convert to string
More on this
Later!
37. Datatypes – regular expressions
• Pattern matching
• Search and replace
/^NITOBI/
/[1-9][0-9]*/
/bnitobib/i
• Use the string method replace
Mystr.replace(/bnitobib/I, “NITOBI”); // capitalize all instances
// of NITOBI.
38. Datatypes – error objects
• Represents a runtime error
• Besides the base Error, there are six other core error types in JavaScript
– EvalError
– RangeError
– ReferenceError
– SyntaxError
– TypeError
– URIError
• Contains the following properties:
More on this
– constructor
Later!
– message try {
– name throw new Error(quot;Whoops!quot;);
– prototype } catch (e) {
alert(e.name + quot;: quot; + e.message);
}
39. Comparing Types
• Equality vs Identity
var a =1;
var b = true;
a == true; // true
a === true; // false
b === true; // true
a !== true; // true
• Inspecting an identifier (typeof)
typeof(a); // “number”
typeof(b); // “boolean”
40. Value vs Reference
• 3 ways to manipulate data values
– Copy it
– Pass it as an argument
– Compare it
• 2 ways to manipulate variables
– By value
– By reference
41. Value vs Reference
// copying by Value
var a = 1;
var b = a; // copy by value.. Two distinct values now
// passing an argument by Value
function add_to_sum(sum, x) {
sum = sum + x; // this only changes the internal
} // copy of x
Won’t actually do
add_to_sum(a,1);
anything
if (b == 1) b = 2; // b is a distinct numeric value
// a is still 1, and b is 2
42. Value vs Reference
// copying by reference
var xmas = new Date(2007, 11, 25);
var gift_day = xmas; // both variables refer to the same object
gift_day.setDate(26); // we’ve now changed both variables
xmas.getDate(); // returns 26 not 25
function add_to_sum(sum, x) { Perman
ent
sum[0] = sum[0] + x; changes ly
‘sum’ in
sum[1] = sum[1] + x; global c
ontext
sum[2] = sum[1] + x;
}
(xmas == gift_day) // this is true still
Note:
var newdate1 = new Date(2007,10,10); Strings are
var newdate2 = new Date(2007,10,10); compared by
(newdate1 == newdate2) // this is false value
44. Typing
• JavaScript is weakly typed
– A variable can hold a value of any type at any
time
m.
i = 10; ro ble
i = “ten”; ,n op
OK
45. Variable Declaration
• Explicit declaration not required
– Implicit declaration has scope consequences
var i; var message = “hello”;
var sum; var i = 0, j = 0, k = 43;
var i, sum;
• Repeated declaration OK too.
var i = 1; // 1
var i = 2; // 2
46. Variable Scope
• Global – available everywhere
• Local – available within a function
• Local > Global
var scope= “global”;
function checkscope() {
var scope = “local”; Note:
pe
console.log(scope); // prints ‘local’; No Block Sco
CH
} except SWIT
& WITH
console.log(scope); // prints ‘global’;
48. Garbage Collection
• Memory allocated and deallocated
automatically
• Interpreter detects when allocated
memory is unreachable
var s = “hello”; // allocate some mem
var u = s.toUpperCase(); // copy the value to a new string
s = u; // “hello” now unreachable and is destroyed
49. JavaScript Gotcha’s
Explorer Memory Leaks
Object A References B
Object A Object B
Object B References A
• Circular references can cause memory
leaks.
51. Operators
Operator Operand type(s) Operation performed
. Object, identifier Property access
[] Array, integer Array index
! Boolean Logical complement
== Any Equality
=== Any Identity
&& Booleans Logical AND
|| Booleans Logical OR
?: Booleans, any, any Conditional operator
, Any Multiple evaluation
52. Assignment with Operation
Operator Example Equivalent
+= a += b a=a+b
-= a -= b a=a–b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b
<<= a <<= b a = a <<b
>>= a >>= b a = a >>b
>>>= a >>>= b a = a >>> b
&= a &= b a=a&b
|= a |= b a=a|b
^= a ^= b a=a^b
53. Conditional Operator (?:)
• Ternary operator (three operands)
greeting = “hello “ + (username != null ? username : “there”);
• is equivalent to..
greeting = “hello “;
if (username != null)
greeting += username;
else Don’t rely
greeting += “there”; on
a compil
er for
code
• Fast, and compact. optimiza
tion
54. Notes about Statements
• Brackets around expressions are required
if (expression)
statement
• Single statements do not require curly-braces
if (expression) if (expression) {
statement statement
statement
}
• Whitespace ignored
if (expression) statement else statement
55. If / else if
• Execute multiple pieces of conditional
code
if (n == 1) { if (n == 1) {
// Execute code block 1 // block 1
} else if (n == 2) { } else {
// Execute code block 2 if (n == 2) {
} else if (n == 3) { // block 2
// Execute block 3 } else {
} else { if (n == 3) {
// if all else fails, do this // block 3
} } else {
// do this
}
}
Equivilent
}
56. Switch
• Better if you are just checking the same var
over and over
switch(n) {
case 1: // start here if n == 1
// code block 1
break;
case 2:
Only use
// code block 2
constants in
break;
C A SE
case 3:
expressions
// code block 3
break;
default: // if all else fails…
// code block 4
break;
}
57. while, do/while
var count = 0;
while (count < 10) {
console.log(count);
count++;
}
var count = 0;
do {
console.log(count);
count++;
} while (count < 10)
Will execute at
least once
58. for
Curly braces {}
for(initialize ; test ; increment) are not required
statement if just one
statement
for (var count = 0; count < 10; count++)
console.log(count);
for(variable in object)
statement
var o = {x:1, y:2, z:3} Copies the object
var a = new Array(); “o” to the array
var I = 0; “a”
for(a[i++] in o) {}
Not all
s a re
propertie
ble!
enumera
59. JavaScript Gotcha’s
Performance Pitfall
lated
re-calcu
IME
E VE R Y T
- !!
• Array.length is expensive --SLOW-
for (var count = 0; count < myarray.length; count++)
console.log(count);
• better:
for (var count = 0, mylen = myarray.length; count < mylen; count++)
console.log(count);
• best:
for (var count = myarray.length-1; count > 0; count--)
console.log(count);
60. labels
• Any statement may be labeled
myloop:
while(something != null) {
// code block
}
• Usually just used for loops
• Used for breaking and continuing
61. break
• Causes the innermost enclosing loop or switch to exit.
break;
• Can be combined with labels
outerloop:
for(var i = 0; i < 10; i++) {
innerloop:
for(var j = 0; j < 10; j++) {
if (j > 3) break; // quit innermost loop
if (i == 2) break innerloop;
if (i == 4) break outerloop;
}
}
62. continue
• Like break.. but just skips to the next
iteration of the current loop
for(i = 0; i < data.length; i++) {
if (data[i] == null)
continue;
total += data[i];
}
• Can be used with labels
63. try/catch/finally/throw
• Create an exception
try {
43534987yhfh // clearly an error
} catch(myerr) {
console.log(myerr);
always executes
} finally {
regardless of what
//code block
happens in catch() or
}
try()
• Custom exceptions
try {
throw(“User entered invalid data..”);
hing
met
} catch(myerr) {
console.log(myerr); “So
w rite ned..”
} finally { Will appe
h
//code block bad
}
64. with
• Code block that modifies the scope chain
with(frames[1].document.forms[0]) {
// access form elements directly here. eg:
name.value = “something”;
address.value = “someplace”;
email.value = “me@home.com”;
}
• Generally avoided.
– slow
– some unexpected behaviors (with init’d vars)
65. ; (empty)
• Has no effect.. but can be useful.
var o = {x:1, y:2, z:3}
var a = new Array();
var I = 0;
for(a[i++] in o) ;
68. Firebug
• Free Firefox plugin (http://www.getfirebug.com)
• Shows you 2 important things:
– What’s going on in your page when it loads
– & After it loads
• Advanced features
• Code profiling
• CSS debugging
• DOM Inspection
• JavaScript breakpoints and step-through
• XHR Debugging
• JSON Object Inspection
• Integration with Aptana
69. MS Script Debugger
• Step over, into
• Console window
• Not much else
• Visual Studio better (if you have it)
70. IE Developer Toolbar
• Useful for debugging CSS in IE
• Lacks many of the features in Firebug
• Convenient cache clearing
• Change CSS attributes on the fly
• Inspect Cache
• DOM browsing
71. Firebug Lite
• JavaScript extension for NON-Firefox
browsers
• Mimics some of the console features of
Firebug
• Evaluate JavaScript in-line
• Makes cross-browser testing a lot easier.
74. JavaScript in the Browser
• JavaScript should be unobtrusive
– Separation of concerns
– Keep it away from markup
– Modularize it
– Degrade gracefully* Sometimes this is real
hard
<html>
<head>
<script type=quot;text/javascriptquot; src=quot;code.js”></script>
</head>
<body>
</body>
</html>
75. Window
• window is global context
• literally means the browser window
• global variables can be referred to as window.variable
• Document object is a member
– Contains a hierarchical representation of document.
• Contains window info
– Geometry
– scroll position
window.innerHeight
window.innerWidth
77. onload Event Handler
• onload fires after all HTML, CSS, Images, and JS is
downloaded to the client.
• At this time, all JavaScript functions and objects part of
the window object have been registered.
<html>
<head>
<script type=quot;text/javascriptquot; src=quot;code.js”></script>
</head>
<body onload=“myFunction()”>
</body>
</html>
78. Document Object Model
• Tree-structure document
• elements, attributes, and text
– text nodes are immutable
79. Form Objects, fields, etc
• Forms are held in a collection
var myForm = document.forms[quot;customerFormquot;];
myForm = document.customerForm;
• Elements accessible as an array or an
object
for (var i = 0, j = myForm.length; i < j; i++)
console.log(myForm[i].value);
console.log(myForm.myname.value);
80. Finding HTML elements
• Get reference to an HTML element
• Use window.document object
• getElementById()
– returns a reference to the first object with the
specified ID
• getElementsByName()
– Returns an array of objects with the specified NAME
attribute
• getElementsByTagName()
– Returns a collection of objects with the specified type (ie DIV,
SPAN, TABLE, etc)
81. innerHTML
• Change the content of HTML element
• Read and Write property
• Cornerstone of AJAX
• Elements must have opening and closing
tags: <p></p> <div></div>
– but not <img />
document.getElementById(‘myId’).innerHTML = “some new text”;
82. setAttribute
• Apply HTML attributes with JavaScript
object.setAttribute(sName, vValue [, iFlags])
var myEl = document.getElementById('info_area');
myEl.setAttribute(quot;classquot;, quot;hoverClassquot;);
83. createElement / appendChild
• Allow you to insert HTML into the DOM
• Faster than adding with innerHTML
– Text nodes are immutable
var myDiv = document.createElement('div');
myDiv.setAttribute(quot;classquot;, quot;hoverClass2quot;);
var body = document.getElementsByTagName('body')[0];
body.appendChild(myDiv);
84. Other ways to create elements
• Four ways to do it
– node.cloneNode(bool) – creates a copy of a node..
and depending on the bool.. copies contents too.
– document.createElement(el) creates a new element
node
– document.createTextNode(txt) creates new text
node
– el.innerHTML – Create elements in text and add to
the DOM that way.
Frowned u
pon.. not
always use
ful. Can be
slow.
85. Adding/Removing Nodes in the
Document
• node.removeChild(oldNode) removes the child oldNode
from node
• node.appendChild(newNode) adds newNode as a new
(last) child node to node
• node.insertBefore(newNode, oldNode) inserts newNode
as a new child node of node before oldNode
• node.replaceChild(newNode, oldNode) replaces the child
node oldNode of node with newNode
86. DOM Navigation
• node.firstChild
– Get the first element of the child array
– same as childNodes[0]
• node.childNodes
– Returns collection of all nodes belonging to that node.. 1st level
only.
• node.parentNode
– Returns the element that this node belongs to
• node.nextSibling
– Returns the next sibling belonging to this elements parent
• node.previousSibling
– Returns the earlier sibling belonging to this elements parent
• chaining:
myNode.childNodes[0].childNodes[2].parentNode.nextSibling.previousSibling;
87. JavaScript Gotcha’s
firstChild & Firefox
• Firefox considers text to be nodes
– when you think about it, this is correct
– but its not that convenient
– whitespace matters
<table>
<tr>
<table><tr><td></td></tr></table> = <td></td>
</tr>
</table>
88. Exercise 1 – DOM Manipulation
• Use JavaScript and the DOM to create this
document: Get optional application template at:
http://www.nitobi.com/gwt/ex1.zip
rr y
Don’t wo
ling
about sty
89. Exercise 1 – Possible Solution
InsertDOM = function() {
var myDiv = document.createElement('div');
var myHeading = document.createElement('h2');
myHeading.innerHTML = quot;Customer Profilequot;;
var myP1 = document.createElement('p');
myP1.innerHTML = quot;Jimmy Smithquot;;
var myDiv2 = document.createElement('div');
myDiv2.innerHTML = quot;Jimmy is married with 2 kids and likes to Golf. Favorite beer
is Molson Export.quot;;
// Here we asseble everything into one node
myDiv.appendChild(myHeading);
myDiv.appendChild(myP1);
myDiv.appendChild(myDiv2);
var body = document.getElementsByTagName('body')[0];
body.appendChild(myDiv);
}
90. Modifying Style Attributes
• Get a reference to the style rule
var myStyle = myElement.style;
• Modify an attribute:
myStyle.backgroundColor = ‘#ffff00’; // yellow
91. DOM Stylesheet (1/2)
• Lets you step through each rule in each stylesheet
• Change selectors
• Read/write styles
• Add new rules
• Affect several elements at same time
• document.styleSheets collection contains all
– cssRules
– href
– other stuff
92. DOM Stylesheet (2/2)
• To find and change a class
– loop through all stylesheets
– look at the selectorText
– modify your style when you’ve found it
if (myRules[k].selectorText == '.specialDiv') {
myRules[k].style.position = 'absolute';
myRules[k].style.top = '100px';
myRules[k].style.left = '100px';
}
93. JavaScript Gotcha’s
Cross Browser Alert!
• In FF/Safari you look for cssRules
• In IE you look for rules
var myRules = (mySheets[i].rules || mySheets[i].cssRules);
95. Threading Model
• JavaScript is single-threaded
• Doc parsing stops when scripts are
embedded
• Browser stops responding to input when
event handlers are executed
• Its possible to mimic multi-threading
96. Pseudo-threading in JavaScript
• Use the timer object to trigger events and
JavaScript processing
– setTimeout
Hypothetical animation
– setInterval
97. A Simple Thread
• Initiate a timer
myGlobalReference = setTimeout(function() {drawObject(50)}, 50);
• Do the work
drawObject = function(x) {
// do some calculation or move an object a few pixels
myGlobalReference = setTimeout(function() {drawObject(x+1)}, 50);
}
• Stop the thread
clearTimeout(myGlobalReference);
99. CSS for DHTML
• Key to dynamic HTML is modifying CSS with JS
Attribute(s) Description
position The type of positioning applied to an element
top,left The position from the top left corner of the parent
width,height Size of the element
z-index Stacking order.. the 3rd dimension
display Whether or not the element is rendered at all
visibility Whether or not the element is visible
overflow What to do with overflow content
opacity How opaque or translucent an element is.. CSS3 attribute. IE has
alternative
100. The KEY to DHTML
• Absolute positioning
– element.style.position = ‘absolute’
– class { position: absolute; }
• Other options:
– relative positioning – position is adjusted
relative to its position in the normal flow
– fixed positioning – relative to the browser
window. NO IE6
101. Position something with JS
• Get the element
myElement = document.getElementById(‘myEL’);
• Set positioning (you could and shouldalso
do this with a class).
myElement.style.position = ‘absolute’;
• Set coordinates
myElement.style.left = ‘20px’;
myElement.style.top = ‘100px’;
102. Exercise 2 – Animation & Threading
• Animate a box resizing itself from 100px /
100px to 300 px / 300 px over several
seconds
Get optional application template at:
http://www.nitobi.com/gwt/ex2.zip
103. Exercise 2 – Possible Solution
AnimateDOMWithThread = function() {
var myDiv = document.createElement('div');
myDiv.style.backgroundColor = quot;#FFFF00quot;;
myDiv.style.width = quot;100pxquot;;
myDiv.style.height = quot;100pxquot;;
myDiv.innerHTML = quot;Some textquot;;
var body = document.getElementsByTagName('body')[0];
body.appendChild(myDiv);
window.myAnimObj = setTimeout(function() {animateBox(myDiv,100, 100)},
20);
}
animateBox = function(myBox, w, h) {
myBox.style.width = w + 'px';
Absolute
myBox.style.height = h + 'px'; positioning
var neww = w+1; var newh = h+1; not required
if ((neww <= 300) || (newh <= 300))
window.myAnimObj = setTimeout(function()
{animateBox(myBox,neww,newh)}, 20);
}
106. Object Oriented JavaScript
• JavaScript is a prototypal language
• Class-based OO programming can be
achieved
Java JavaScript
Strongly Typed Loosely Typed
Static Dynamic
Classical Prototypical
Classes Functions
Constructors Functions
Methods Functions
107. Functions are Objects Too
• Important function methods:
– call(scope, arg1, arg2 …);
– apply(scope, [arg1, arg2 …]);
– caller
• Call and apply used to dynamically
execute a function in arbitrary scope
108. Using Call
function showLength() {
alert(this.length);
}
“this” refers to the new
Array
showLength.call(new Array(10)); // Alerts 10!
109. First, a review of an object
• This is an object
Person = function(fn, ln) {}
110. Public Members
• Use this keyword
Person = function(fn, ln) {
this.firstName = fn;
this.lastName = ln;
}
Person.prototype.getFullName = function() {
return this.firstName + “ “ + this.lastName;
}
var a = new Person(“Alex”, “White”);
console.log(a.firstName) // “Alex”
111. Private Members
• Local scope variables.
• Only accessible from within the
constructor
Person = function(fn, ln) {
var firstName = fn;
var lastName = ln;
var getFullName = function() {
return firstName + “ “ + lastName;
}
}
112. Privileged Members
• getFullName creates closure and therefor
exposes private vars through a getter();
Person = function(fn, ln) {
var firstName = fn;
var lastName = ln;
this.getFullName = function() {
return firstName + quot; quot; + lastName;
}
}
113. Classical JavaScript
• A Function() is a constructor
• Can use new keyword to instantiate to
create new instances (copy).
Person = function() {
}
var john = new Person();
• Use this to add instance methods and
properties
Person = function() {
this.age = 12;
}
114. Basic Non-prototypal Class
• Start with a rectangle:
Rectangle = function(w, h) {
this.width = w;
this.height = h;
this.area = function() {return this.width*this.height;}
}
• Create an instance:
var r = New Rectangle(10,20);
var a = r.area(); // 200;
• Innefficient, memory hungry, inflexible
115. Classical JavaScript
• Use “prototype” keyword to define
instance properties and methods
• Same result different approach
Rectangle = function(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width*this.height;
}
var r = New Rectangle(10,20);
var a = r.area(); // 200;
116. Another Advantage – Change the
class
• Modify the prototype to add functionality
to all instances of that prototype
<!-- … -->
Rectangle.prototype.widthSquared = function() {
return this.width*this.width;
}
// var r = New Rectangle(10,20); -- OUR OLD Rectangle OBJECT
var ws = r.widthSquared(); // 100;
117. Classical Inheritance
• The simple approach
PositionedRectangle = function(x,y,w,h) {
Rectangle.call(this,w,h);
// Now we store the left and right coords
this.x = x;
this.y = y;
}
PositionedRectangle.prototype = new Rectangle();
118. Inheritance – Simple Approach
• Why this might be bad
– Explicit reference to Rectangle in the
constructor – brittle ork
Will still w s
ase
PositionedRectangle = function(x,y,w,h) { in most c
Rectangle.call(this,w,h);
<!-- … -->
– Constructor assigned to prototype –
potentially brittle at compile-time if DOM is
being drawn
PositionedRectangle.prototype = new Rectangle();
119. Inheritance Function remove compile-
time constructor
extend = function(subClass, baseClass) { execution
function inheritance() {};
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance(); base constructor
subClass.baseConstructor = baseClass; pointer
if (baseClass.base) {
baseClass.prototype.base = baseClass.base;
}
base method
subClass.base = baseClass.prototype;
pointers
}
Customer = function (firstName, lastName) {
Customer.baseConstructor.call(this, firstName, lastName);
this.balance = 0;
}
Customer.prototype.getFullName = function() {
Customer.base.getFullName.call(this);
}
extend(Customer, Person);
120. More on the many ways to Inherit
• http://truecode.blogspot.com/2006/08/ob
ject-oriented-super-class-method.html
• Douglas Crockford – my hero
– http://www.crockford.com/javascript/inherita
nce.html
121. Classical Interfaces - Mixins
• No compilation in JavaScript so interfaces
are tough
• Need to rely on mutability of JavaScript
objects or “mixins”
var customer1 = new Customer();
var customer2 = new Customer();
customer1.pay = function(amout) {
this.balance -= amount;
}
customer1.pay();
customer2.pay(); // ERROR!
122. Classical Interfaces - Mixins
• Mutate classes at runtime
• Think of the implications for AOP
var customer1 = new Customer();
var customer2 = new Customer();
Customer.prototype.pay = function(amount) {
this.balance -= amount;
}
customer1.pay(); var f = Customer.oldFunction
customer2.pay(); Customer.oldFunction = function() {
f.call(this);
somethingElse();
}
125. XMLHttpRequest
• The core of Ajax
IE 6 and 7
var xhr = null;
try {
xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;);
} catch(e) {
xhr = new XMLHttpRequest(); Everybody Else
}
xhr.open(quot;GETquot;, quot;http://www.example.com/myResourcequot;, false);
xhr.send(null);
showResult(xhr);
Async = false
126. XHR Factory
• Use Factory pattern to create XHR objects
in a cross-browser manner
xhrFactory = {
create: function() {
try {
xhr = new ActiveXObject(quot;Microsoft.XMLHTTPquot;);
} cstch(e) {
xhr = new XMLHttpRequest();
}
return xhr;
}
}
var xhr = xhrFactory.create();
127. Synchronous Requests
• Simplest case
• However, JavaScript thread is locked!
var xhr = xhrFactory.create();
xhr.open(quot;GETquot;, “http://www.example.com/resource”, false);
var response = xhr.send(null);
Async = false
128. Asynchronous Requests
• Use async requests to prevent locking the
JavaScript thread
xhr.open(quot;GETquot;, “http://www.example.com/resource”, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) { Async = true
// deal with the response
}
} Regular HTTP status code
}
129. Request Types
• GET
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);
• POST
xhr.open(“POST”, “http://www.example.com/resource”, false);
var response = xhr.send(“firstName=john&lastName=doe”);
130. Data Types
• POST data to the server as either XML or
form encoded data
• Use XHR setRequestHeader() method
XML
xhr.setRequestHeader(quot;Content-Typequot;,quot;text/xmlquot;);
Form data
xhr.setRequestHeader(quot;Content-Typequot;,quot;application/x-www-form-urlencodedquot;);
131. Response Data
• We can expect the response from the
server as XML, JSON, HTML or text
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);
alert(response.responseXml); // Should show a [Document] for XML response
alert(response.responseText); // Should show the XML, JSON, or HTML data
e
Make sur
e
you set th
type
response
r ver
on the se
too!
132. What Type of Response?
• XML
– Good for Web Services and XML RPC
– A bit more work on the client.. browser
differences
• JSON
– Easy, fast Just yse
what
r…..
you prefe
• HTML
– No rendering logic on client
– bandwidth considerations
133. XML Response
• Various ways of dealing with XML data
– XML DOM – most compatible
– XPath – fast and easy
– XSLT – not supported everywhere
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);
var html = “”;
var customers = response.responseXml.getElementsByTagName(“customer”);
for (var i=0; i<customers.length; i++) {
var customer = customers[i];
html += “<div>”+customer.childNodes[0].nodeValue+”</div>”;
html += “<div>”+customer.childNodes[1].nodeValue+”</div>”;
}
alert(html);
134. JSON Response
• Need to instantiate the data into
JavaScript objects
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);
var html = “”;
var customers = eval(“(“+response.responseText+”)”);
// OR eval(“a = “ + response.responseText);
for (var i=0; i<customers.length; i++) {
var customer = customers[i];
html += “<div>”+customer.firstName+”</div>”;
html += “<div>”+customer.lastName+”</div>”;
}
alert(html);
135. HTML Response
• Take the HTML from the server and put it
into the web page DOM
xhr.open(“GET”, “http://www.example.com/resource”, false);
var response = xhr.send(null);
var html = response.responseText
alert(html);
136. Cross-Domain XHR
• Create <script> element dynamically
var script = document.createElement(“script”);
script.src = “http://www.example.com/resource?callback=myCallback”;
document.getElementsByTagName(“head”)[0].appendChild(script);
• Response from server includes JavaScript
and calls a callback function
Dynamically generated
• Called JSONP or XMLP function call
var customers = [{firstName:”John”,lastName:”Doe”}]
myCallback(customers);
137. JavaScript Gotcha’s
Cross-Domain JSONP Security
• There are serious security risks with JSON
or XMLP
• Also serious risks with JSON in general
– Return JSON data in comments to prevent
non XHR access
<!--
[{firstName:”John”,lastName:”Doe”}]
-->
139. DOM Events
• Native Event object contains information
about the event
• Two approaches to defining events:
– Inline
– Unobtrusive
• Unobtrusive approach requires cross-
browser event attachment
141. JavaScript Gotcha’s
onload Event
• Need the page JavaScript to execute as
soon as possible
• onload waits for all images etc to load
Firefox
if (document.addEventListener)
document.addEventListener('DOMContentLoaded', init, false);
Internet Explorer
<!--[if IE]><script defer src=quot;ie_onload.jsquot;></script><![endif]-->
The rest
window.onload = init;
142. Inline Events
• Most simple event attachment
<div onmouseover=“swapColor(event)” onmouseout=“swapColor(event)”></div>
• What about separating our control from
our view?
143. DOM Event Decoration
• Attach event handlers to DOM nodes
through JavaScript
var domNode = document.getElementById(“myNode”);
domNode.onmouseover = highlight;
Function pointer
• This can create memory leaks when using
Most common way of creating
anonymous functions memory leaks in IE
var domNode = document.getElementById(“myNode”);
domNode.onmouseover = function() { domNode.style.color = ‘red’;};
144. JavaScript Gotcha’s
DOM Event Decoration
W3C - Firefox Captur
e
var domNode = document.getElementById(“myNode”);
domNode.addEventListener(“mouseover”, hightlight, false);
Function pointer
Internet Explorer
var domNode = document.getElementById(“myNode”);
domNode.attachEvent(“onmouseover”, highlight);
Prefixed with “on”
145. JavaScript Gotcha’s
Event Object
Internet Explorer W3C document.documentElement.clientHeight
clientX / Y returns the event coordinates without the document scroll position
clientX / Y clientX / Y, pageX / Y taken into account, whereas pageX / Y does take
scrolling into account.
N/A currentTarget The HTML element to which the event handler was attached.
Various key event modifiers to check if ctrlKey, shiftKey ctrlKey, shiftKey the
keyCode, altKey, ctrlKey, shiftKey keyCode, altKey, ctrlKey, shiftKey
Shift or Ctrl key are pressed.
The HTML element on which the event actually took place. Both properties are
srcElement target
supported in Opera and Safari.
type type The event type without the “on” prefix.
from is used only for mouseover and mouseout events. Both properties are
fromElement / toElement relatedTarget
supported in Opera and Safari
146. Event Questions
• How do you access the Event object?
• What does “this” refer to in the event
handler function?
147. Event Object
• Passed as argument to event handler in
W3C model and as a global in IE
W3C
function swapColor(evt) {
}
Internet Explorer
function swapColor() {
var evt = window.event;
}
148. Handler Execution Scope
• “this” is the element that handled the
event (W3C) or the window (IE)
W3C
function swapColor(evt) {
this.style.color = “#FF0000”;
}
Internet Explorer
function swapColor() {
window.event.srcElement.style.color
}
149. Cross-Browser Event Façade
• Make Internet Explorer look like W3C
eventManager = {}; // Singleton object Event type “mouseover”, etc
eventManager.attachEvent = function(elem, type, handler, capture) {
// Browser checking for IE vs W3C compliant browser
if (elem.attachEvent) { Detects IE
// Create two expando properties with function references
elem[‘evt_' + type] = function() {
handler.call(elem);
}; Sets scope of “this”
// Attach one of our expando function references to the event
IE elem.attachEvent('on'+type, elem[‘evt_' + type]);
// Set the capture if it was specified
if (capture) elem.setCapture(true);
} else if (elem.addEventListener) {
W3C elem.addEventListener(type, handler, capture);
}
}
150. Event Flow
• Events have two phases
– Events are first captured and propagate from
the <body> to the target element
– Event then bubbles back up from the target
element to the <body>
• Capture is very different in IE and W3C but
important nonetheless
152. Event Creation
• Programmatic event creation
if (window.attachEvent) // Internet Explorer
{
element.fireEvent('on'+evtName);
}
else
{
// create and init a new event
var newEvent = document.createEvent(evtType);
newEvent.initKeyEvent(evtName, true, true, document.defaultView,
ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode);
// dispatch new event
element.dispatchEvent(newEvent);
}
153. Exercise 3 – OO JavaScript (if time)
• Create the following objects:
– Person class
• age Get optional application template at:
• name http://www.nitobi.com/gwt/ex3.zip
• height
– Customer class
• account balance
• inherits from Person
• Put at least 1 prototype method on each class.
• Create a few customers