2. About Me
Programmer since (gulp) 1979
Paid programmer since 1985
Java programmer since January 1995
Co-founder of JavaMUG
Author of first advanced Java book
Speaker at No Fluff, Just Stuff since 2003
Independent consultant, trainer, and speaker
Ruby, Agile, TDD, JavaScript, Ajax
3. About This Talk
My full introduction to JavaScript is 3 hours
… and it could easily be much longer.
This talk does get technical …
But first, it’s worth recalling how we got here.
5. Cast Your Mind Back …
January 1995: first public demonstration of Java
May 1995: Netscape licenses Java
October 1995: Navigator 2.0B1 supports Java
… and we hear the first mention of a web-page-based scripting
language called LiveScript.
The web is all abuzz about the coolness and potential of applets.
December 1995: Netscape renames LiveScript to
JavaScript and unveils it in Navigator 2.0B3
March 1996: First JavaScript talk at JavaMUG (by Greg
Graham)
6. A Bad Beginning
The decision to link JavaScript with Java—in
name and in syntax—proved to be a terrible one.
Clearly, Java programmers were in the best
position to understand and begin teaching it,
right?
7. “It’s a Toy!”
We early Java programmers took one look at
JavaScript and were revolted.
“Everything’s public!”
“No subclassing!”
“You can add and remove methods on existing objects!”
“You can change a property to a method!”
“I don’t know how to understand this language!!!”
JavaScript was a 10-day hack that got shipped.
We could tell.
8. The Result
Java programmers say “Avoid JavaScript.”
Keep all your logic on the server.
That’s where it belongs.
Use a real programming language.
Second JavaScript talk at JavaMUG?
George Lawniczak, “Ajax 101”, March 2006
A 10-year gap
10. Then, Things Got Ugly
Applets failed.
With nothing else useful to do, JavaScript became a
tool for flash and dazzle.
Widespread abuse.
Annoying layers that obscured the useful part of the
page.
Poorly tested JavaScript. Runtime bugs.
Security issues that prompted people to turn
JavaScript off.
Flashing images, scrolling status bars. Blechh.
11. Nature Abhors
a Vacuum
Java people showed no interest in learning to use
JavaScript well.
So the page designers filled the gap.
Widespread examples of poor JavaScript style.
Some in pages, some in books.
Nearly everyone learned JavaScript from those examples.
They failed to see the potential, except for visual effects.
Learning a language by example works well …
if the language is similar to what you already know.
12. You Ain’t Seen Ugly
Yet
Then: The Browser Wars
JavaScript was a primary weapon.
Along with the DOM
Rapid change, competing standards
Willful incompatibility
Infuriating bugs
13. … and Yet …
All along, I kept hearing people pay grudging
respect to JavaScript.
“It’s similar to NewtonScript.”
I knew enough about NewtonScript and its ancestor,
Self, to know that was a compliment.
“It would be great except for the browser.”
15. End of Browser Wars
Netscape gives up.
Mozilla and Firefox call a truce.
Microsoft shifts bug ray to CSS.
JavaScript implementations are actually pretty
good.
IE includes XMLHttpRequest, and Mozilla
follows suit.
How long before Java programmers wake up and
notice the changed situation?
16. Signs of Life
2000: Brent Ashley
Remote Scripting Resources site: www.ashleyit.com/rs/
JSRS (JavaScript Remote Scripting) and RSLite
2000: Alex Russell
netWindows (which became nWidgets, which gave rise
to Dojo)
Brent and Alex (and a few others) began exploring
the power of JavaScript and Ajax, long before that
term was invented.
17. Growth Outside
the Browser
Also during this period, JavaScript became the
default choice for an embedded scripting and
extension language.
Flash (ActionScript is a dialect of JavaScript)
Adobe applications: Photoshop, Illustrator, Acrobat,
etc.
Cocoon
Mac OS X apps: Sherlock, Konfabulator, Dashboard
Mozilla platform
MKS SourceIntegrity
18. It’s Always Darkest
Before Dawn
I don’t know the whole story of this period.
I was asleep in Java land.
June 2003: David Raphael showed me
netWindows, and I woke up.
25. My First Fluent
JavaScript
Budgeting/forecasting/three-year-planning app
Restaurants
Groceries
Meals
Car
Plane
Taxis
Transportation
Grand Total
2007
500
300
800
400
2,400
200
3,000
3,800
2008
450
300
750
500
2,200
250
2,950
3,700
2009
Total
425
1,375
275
875
700
2,250
550
1,450
2,100
6,700
300
750
2,950
8,900
3,650 11,150
26. Solution:
The Totalizator
to•tal•i•za•tor ¦ tōtl-i zātər¦
noun
A machine for computing and showing totals,
especially a pari-mutuel machine showing the
total number and amounts of bets at a
racetrack.
(The American Heritage Dictionary of the English Language,
Fourth Edition)
27. Solution:
The Totalizator
Table marked with an id attribute
Total column marked with total-column class
Subtotal rows marked with subtotal-row class
Grand total row marked with grand-total class
new Totalizator(‘forecast_table’);
28. How the Totalizator
Worked
Find the table using
document.getElementByID(table_id).
Traverse it looking for cells of various types,
building quick-reference lists.
Total everything up and set content in all total
cells.
Set observers on text fields to prompt
recalculation when cells are updated.
30. So Far, So Good
But it was a CRUD app.
My first version of Totalizator was great for
Create and Update.
Not necessary for Delete
What about Read?
Looking for text fields to observe ... we just don’t find
any.
Only other problem is reading a number from a cell.
32. What To Do?
Add an if statement to getNumberFromCell.
Nope. Too clumsy and specialized.
Remember: the only numbers are 0, 1, and many.
Write a subclass! ReadOnlyTotalizator!
Seems wrong somehow.
Plus, JavaScript doesn’t directly support subclasses.
I know! Use the Strategy pattern!
Killing flies with a bazooka …
33. Stop Thinking Java!
Functions are first-class objects in JavaScript.
Methods are just functions attached to objects.
You can add methods to classes at any time.
(Even after instances have been created.)
Individual objects can have their own methods!
34. An Easy Solution
function Totalizator(table_id, gnfc_function) {
this.table_id = table_id;
this.getNumberFromCell = gnfc_function;
// process table and find cells
}
new Totalizator(‘forecast_table’, function(cell) {
// logic to get number out of cell
});
35. That’s Easy?
Easy for Glenn to implement, maybe.
Not so easy for someone to use.
You have to supply a missing method every time
you create an instance!!!
36. Yeah, It’s Easy
Nobody said I couldn’t supply some useful
implementations …
Totalizator.getNumberFromSimpleCell = function(cell) {
return Number(cell.innerHTML);
}
Totalizator.getNumberFromTextInputCell = function(cell) {
return Number(cell.children[0].value);
}
Totalizator.prototype.getNumberFromCell =
Totalizator.getNumberFromSimpleCell;
37. One Final Update
Quickly revisit the constructor:
function Totalizator(table_id, gnfc_function) {
this.table_id = table_id;
if (arguments.length > 1)
this.getNumberFromCell = gnfc_function;
// process table and find cells
}
Now there’s some flexibility when creating:
new Totalizator(‘forecast_table’);
new Totalizator(‘forecast_table’,
Totalizator.getNumberFromTextInputCell);
38. How Does That Feel?
Sloppy? Maybe, if you’re still thinking in Java.
JavaScript is dynamic for good reasons.
Overengineered? I don’t think so.
Took a tiny bit of effort.
Easy to document.
Nice and DRY.
But you have to know the language!
39. What We Had to Know
Functions are first-class objects in JavaScript.
Methods are just functions attached to objects.
You can add methods to classes at any time.
(Even after instances have been created.)
Individual objects can have their own methods.
“Class” “constructors” are just functions.
Functions can have their own properties.
The arguments array lets you reflect on the argument list.
You can call functions or methods with too few (or too many)
arguments.
40. When we use a language,
we should commit ourselves to
knowing it, being able to read it,
and writing it idiomatically.
—Ron Jeffries
41. “The august Waldemar Horwat—who
was at one time the lead JavaScript
developer at Netscape—once told me that
he considered JavaScript to be just
another syntax for Common Lisp. I’m
pretty sure he was being serious.”
—Eric Lippert
42. JavaScript Is Weird
… unless you know NewtonScript or Self
(or, to a lesser degree, Smalltalk or CLOS)
Let’s look at a couple of the more interesting
aspects.
44. Functions Are Objects
The following two statements are equivalent:
function square(num) { return num*num; }
var square = function(num) { return num*num; };
You can use functions without names
Functions can (and do) have their own properties.
46. Variable Scope
In global scope, variables are resolved through
the global object.
add(accum, incr)
global
accum: 1
incr: 2
add: <function>
47. Variable Scope
Let’s see what happens in the body of that
function.
function add(a, b) {
return a + b;
}
<call>
__parent__:
a: 1
b: 2
arguments: [1, 2]
global
accum: 1
incr: 2
add: <function>
48. Lexical Scope
function f(x, y) {
g(x);
}
function g(z) {
alert(z);
}
f(3, 4);
What does the scope
chain look like when
alert is called?
global
f: <function>
g: <function>
alert: <function>
<call>
__parent__:
z: 3
arguments: [3]
49. Lexical Scope
function f(x, y) {
function g(z) {
alert(y);
alert(z);
}
g(x);
}
f(3, 4);
Does this change the
scope chain?
global
f: <function>
alert: <function>
<f’s call>
__parent__:
g: <function>
x: 3
y: 4
arguments: [3, 4]
<g’s call>
__parent__:
z: 3
arguments: [3]
50. Variable Scope:
Closures
That works even for
anonymous functions:
function f(x, y) {
return function (z) {
alert(y);
alert(z);
}
}
global
f: <function>
g: <function>
alert: <function>
<f’s call>
__parent__:
x: 3
y: 4
arguments: [3, 4]
<g’s call>
g = f(3, 4);
g(5)
__parent__:
z: 5
arguments: [5]
51. Variable Scope:
Closures
As part of XMLHttpRequest’s API, you must
supply callback functions.
XHR won’t pass them any parameters.
What if, in response to one of the XHR events,
you want to do some fairly complicated
processing with an element?
52. Variable Scope:
Closures
function ajaxDazzle() {
if (xhr.readyState != 4) return;
elem = document.getElementByID(‘item_list’);
// do complicated stuff
}
// …
xhr.onreadystatechange = ajaxDazzle;
OK, but what if ‘item_list’ isn’t the only element
you need this for?
53. Variable Scope:
Closures
function ajaxDazzler(elem_id) {
return function() {
if (xhr.readyState != 4) return;
elem = document.getElementByID(elem_id);
// do complicated stuff
};
}
// …
xhr.onreadystatechange = ajaxDazzler(‘item_list’);
55. Instance Variables
in Java
object.prop;
What happens?
Java finds the value of prop directly in the object.
But where does it come from?
At creation, all instance variables are created based on
declarations in the class and all superclasses.
56. Instance Variables
in JavaScript
object.prop;
What happens?
JavaScript looks for the value of prop directly in the
object.
If not found there, it looks in the object referenced by
the __proto__ property (usually the constructor’s
prototype).
The search continues until prop is found or __proto__ is
null.
57. Instance Variables
in JavaScript
But where does it come from?
Properties are usually created by the constructor.
Sometimes they already exist on the prototype when
the instance is created.
Often they’re added (in either place) after creation,
whether by a method or from the outside.
Point
point1
__proto__:
x: 1
y: 2
<prototype>
__proto__: <other prototype>
constructor: <function Foo>
name: “unnamed”
prototype:
58. Methods in Java
object.method();
What happens?
Java looks for prop in the object’s class.
If it’s not there, look in superclass.
Continue until found or superclass is null.
But where does it come from?
All methods are declared within classes when the
classes are declared.
59. Methods in JavaScript
object.method();
What happens?
JavaScript looks for the value of method directly in the
object.
If not found there, it looks in the object referenced by
the __proto__ property (usually the constructor’s
prototype).
The search continues until method is found or
__proto__ is null.
60. Instance Variables
in JavaScript
But where does it come from?
Methods are usually set on the prototype before the
instance is created.
Sometimes they’re created by the constructor.
Often they’re added (in either place) after creation,
whether by a method or from the outside.
Point
point1
__proto__:
x: 1
y: 2
to_polar: <function>
<prototype>
__proto__: <other prototype>
constructor: <function Foo>
name: “unnamed”
distance: <function>
prototype:
61. Properties
and Methods
In Java, instance variables and methods are very
different.
In JavaScript, they’re the same.
They’re usually created in different ways, but that’s just
the way people do it.
Neither works exactly the way they do in Java.
This can come in handy!
Add methods to individual objects.
Add an instance variable to all existing instances.
62. There’s More …
It’s all incredibly handy, once you embrace the
JavaScript philosophy.
Would I build an application server with it?
Probably not.
I wouldn’t port Swing to it, either.
But it’s remarkably well suited for the
environment inside a web page.
63. The really important thing
about Ajax is that it’s tricked us
into adopting a really powerful
language when we wouldn’t have
chosen to do so on our own.
—Stuart Halloway
64. Ajax is a gateway drug
for JavaScript.
—Stuart Halloway