64
Glenn Vanderburg [email protected] Learning to Love JavaScript

Glenn Vanderburg — Learning to love JavaScript

  • Upload
    atr2006

  • View
    418

  • Download
    0

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Glenn Vanderburg — Learning to love JavaScript

Glenn [email protected]

Learning to Love JavaScript

Page 2: Glenn Vanderburg — Learning to love JavaScript

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 speakerRuby, Agile, TDD, JavaScript, Ajax

Page 3: Glenn Vanderburg — Learning to love JavaScript

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.

Page 4: Glenn Vanderburg — Learning to love JavaScript

Comfortable Confusion

Part I

Page 5: Glenn Vanderburg — Learning to love JavaScript

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)

Page 6: Glenn Vanderburg — Learning to love JavaScript

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?

Page 7: Glenn Vanderburg — Learning to love JavaScript

“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.

Page 8: Glenn Vanderburg — Learning to love JavaScript

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

Page 9: Glenn Vanderburg — Learning to love JavaScript

Collateral Damage

Part II

Page 10: Glenn Vanderburg — Learning to love JavaScript

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.

Page 11: Glenn Vanderburg — Learning to love JavaScript

Nature Abhorsa 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.

Page 12: Glenn Vanderburg — Learning to love JavaScript

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

Page 13: Glenn Vanderburg — Learning to love JavaScript

… 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.”

Page 14: Glenn Vanderburg — Learning to love JavaScript

Reconstruction

Part III

Page 15: Glenn Vanderburg — Learning to love JavaScript

End of Browser WarsNetscape 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?

Page 16: Glenn Vanderburg — Learning to love JavaScript

Signs of Life

2000: Brent AshleyRemote Scripting Resources site: www.ashleyit.com/rs/

JSRS (JavaScript Remote Scripting) and RSLite

2000: Alex RussellnetWindows (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.

Page 17: Glenn Vanderburg — Learning to love JavaScript

Growth Outsidethe 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

Page 18: Glenn Vanderburg — Learning to love JavaScript

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.

Page 19: Glenn Vanderburg — Learning to love JavaScript

Revolution

Part IV

Page 20: Glenn Vanderburg — Learning to love JavaScript

The Revolution Began with Google

Google Mail

Google Suggest

Google Maps

You know the rest. Now there are uncounted Ajax applications.

Page 21: Glenn Vanderburg — Learning to love JavaScript

Toolkits, Frameworks, Tools

Many JavaScript libraries and toolkits to choose from.

Prototype, Scriptaculous, Dojo, OpenRico, MochiKit, DWR, YUI, Kabuki, …

End-to-end web frameworks rolling in Ajax support.

Rails, Tapestry, JSF, ASP.NET, Seaside, Struts, WebWork, …

Specialized tools for Ajax developmentLinks, GWT, Hop, Echo2, OpenLaszlo, haXe, …

Page 22: Glenn Vanderburg — Learning to love JavaScript

Livin’ la Vida Loca

Part V

Page 23: Glenn Vanderburg — Learning to love JavaScript

No Rules,Just Right

– or –

Page 24: Glenn Vanderburg — Learning to love JavaScript

Stop Worrying and Love the DOM

– or –

Page 25: Glenn Vanderburg — Learning to love JavaScript

My First Fluent JavaScript

Budgeting/forecasting/three-year-planning app

2007 2008 2009 TotalRestaurants 500 450 425 1,375

Groceries 300 300 275 875Meals 800 750 700 2,250

Car 400 500 550 1,450Plane 2,400 2,200 2,100 6,700Taxis 200 250 300 750

Transportation 3,000 2,950 2,950 8,900Grand Total 3,800 3,700 3,650 11,150

Page 26: Glenn Vanderburg — Learning to love JavaScript

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)

Page 27: Glenn Vanderburg — Learning to love JavaScript

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’);

Page 28: Glenn Vanderburg — Learning to love JavaScript

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.

Page 29: Glenn Vanderburg — Learning to love JavaScript

Totalizator Methods

buildDependentCellLists() doTotals()

findAllCells() getNumberFromCell(cell)

registerRow(row) registerDataRow(row)

registerSubtotalRow(row) registerTotalRow(row)

sumCells(cells) updateCells(dependents)

updateDependents(element)

Page 30: Glenn Vanderburg — Learning to love JavaScript

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.

Page 31: Glenn Vanderburg — Learning to love JavaScript

The Problem Method

buildDependentCellLists() doTotals()

findAllCells() getNumberFromCell(cell)

registerRow(row) registerDataRow(row)

registerSubtotalRow(row) registerTotalRow(row)

sumCells(cells) updateCells(dependents)

updateDependents(element)

Page 32: Glenn Vanderburg — Learning to love JavaScript

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 …

Page 33: Glenn Vanderburg — Learning to love JavaScript

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!

Page 34: Glenn Vanderburg — Learning to love JavaScript

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});

Page 35: Glenn Vanderburg — Learning to love JavaScript

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!!!

Page 36: Glenn Vanderburg — Learning to love JavaScript

Yeah, It’s EasyNobody 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;

Page 37: Glenn Vanderburg — Learning to love JavaScript

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);

Page 38: Glenn Vanderburg — Learning to love JavaScript

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!

Page 39: Glenn Vanderburg — Learning to love JavaScript

What We Had to KnowFunctions 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.

Page 40: Glenn Vanderburg — Learning to love JavaScript

When we use a language,we should commit ourselves to

knowing it, being able to read it, and writing it idiomatically.

—Ron Jeffries

Page 41: Glenn Vanderburg — Learning to love JavaScript

“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

Page 42: Glenn Vanderburg — Learning to love JavaScript

… 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.

JavaScript Is Weird

Page 43: Glenn Vanderburg — Learning to love JavaScript

Functions and Scope

Page 44: Glenn Vanderburg — Learning to love JavaScript

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.

Page 45: Glenn Vanderburg — Learning to love JavaScript

FunctionsWithout Names?

(function(a, b){ return a+b; })(3, 4);

Page 46: Glenn Vanderburg — Learning to love JavaScript

Variable Scope

In global scope, variables are resolved through the global object.

add(accum, incr)

globalaccum: 1incr: 2add: <function>

Page 47: Glenn Vanderburg — Learning to love JavaScript

Variable Scope

Let’s see what happens in the body of that function.function add(a, b) { return a + b;}

globalaccum: 1incr: 2add: <function>

<call>__parent__:a: 1b: 2arguments: [1, 2]

Page 48: Glenn Vanderburg — Learning to love JavaScript

Lexical Scopefunction f(x, y) { g(x);}

function g(z) { alert(z);}

f(3, 4);

What does the scope chain look like when alert is called?

globalf: <function>g: <function>alert: <function>

<call>__parent__:z: 3arguments: [3]

Page 49: Glenn Vanderburg — Learning to love JavaScript

Lexical Scopefunction f(x, y) { function g(z) { alert(y); alert(z); }

g(x);}

f(3, 4);

Does this change the scope chain?

globalf: <function>alert: <function>

<g’s call>__parent__:z: 3arguments: [3]

<f’s call>__parent__:g: <function>x: 3y: 4arguments: [3, 4]

Page 50: Glenn Vanderburg — Learning to love JavaScript

Variable Scope: Closures

That works even for anonymous functions:

function f(x, y) { return function (z) { alert(y); alert(z); }}

g = f(3, 4);g(5)

globalf: <function>g: <function>alert: <function>

<g’s call>__parent__:z: 5arguments: [5]

<f’s call>__parent__:x: 3y: 4arguments: [3, 4]

Page 51: Glenn Vanderburg — Learning to love JavaScript

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?

Page 52: Glenn Vanderburg — Learning to love JavaScript

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?

Page 53: Glenn Vanderburg — Learning to love JavaScript

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’);

Page 54: Glenn Vanderburg — Learning to love JavaScript

Instance Variables and Methods

Page 55: Glenn Vanderburg — Learning to love JavaScript

Instance Variablesin 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.

Page 56: Glenn Vanderburg — Learning to love JavaScript

Instance Variablesin 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.

Page 57: Glenn Vanderburg — Learning to love JavaScript

Instance Variablesin 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.

<prototype>__proto__: <other prototype>constructor: <function Foo>name: “unnamed”

point1__proto__:x: 1y: 2

Pointprototype:

Page 58: Glenn Vanderburg — Learning to love JavaScript

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.

Page 59: Glenn Vanderburg — Learning to love JavaScript

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.

Page 60: Glenn Vanderburg — Learning to love JavaScript

Instance Variablesin 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.

<prototype>__proto__: <other prototype>constructor: <function Foo>name: “unnamed”distance: <function>

point1__proto__:x: 1y: 2to_polar: <function>

Pointprototype:

Page 61: Glenn Vanderburg — Learning to love JavaScript

Propertiesand 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.

Page 62: Glenn Vanderburg — Learning to love JavaScript

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.

Page 63: Glenn Vanderburg — Learning to love JavaScript

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

Page 64: Glenn Vanderburg — Learning to love JavaScript

Ajax is a gateway drugfor JavaScript.

—Stuart Halloway