Advanced JavaScript
Writing Reusable Code
Thursday, July 12, 12
Slide 2
Slide 2 text
Agenda
JavaScript History
Language Overview
Arrays & Objects
Functions
Thursday, July 12, 12
Slide 3
Slide 3 text
The World’s Most
Misunderstood
Programming Language
Thursday, July 12, 12
Slide 4
Slide 4 text
History
1995 Brendan Eich started
developing a new language
for Netscape Navigator 2.0
Original name was
LiveScript
Announced on Dec 1995 as
JavaScript
1996 Microsoft responded
with JScript
Thursday, July 12, 12
Slide 5
Slide 5 text
JS Today
Used for Client side
development on
desktop and mobile
Used for Server side
development using
NodeJs
Embedded in
applications using
Rhino
Thursday, July 12, 12
Slide 6
Slide 6 text
Language Overview
JavaScript is not a toy
JavaScript has nothing to do with Java
JavaScript is a powerful programming language
on its own
Thursday, July 12, 12
Slide 7
Slide 7 text
JavaScript Key Ideas
Interpreter based (no compilation)
Loosely typed language
Objects are just hash tables
Prototypical inheritance model
Functions are regular objects (with a twist)
Arrays are regular objects (with a twist)
Thursday, July 12, 12
JavaScript Gotchas
var x = “3”;
var y = 5;
x + y == 8;
x + y == 35;
x + y === 35;
Thursday, July 12, 12
Slide 10
Slide 10 text
JavaScript Gotchas
var x = “3”;
var y = 5;
x + y == 8; // false
x + y == 35; // true
x + y === 35; // false
Thursday, July 12, 12
Slide 11
Slide 11 text
JavaScript Gotchas
function foo() {
return
{
val : 3
}
}
function bar() {
return { val : 3 }
}
var x = foo();
var y = bar();
x.val == y.val;
Thursday, July 12, 12
Slide 12
Slide 12 text
JavaScript Gotchas
// returns undef
function foo() {
return
{
val : 3
}
}
// returns object
function bar() {
return { val : 3 }
}
var x = foo();
var y = bar();
x.val == y.val; // error
Thursday, July 12, 12
Q & A
JavaScript History
Language Overview
Arrays & Objects
Functions
Thursday, July 12, 12
Slide 16
Slide 16 text
Objects
JS Objects are container for data
A data field in an object is a name-value pair
The name can be any string
The value can be anything except undefined
Thursday, July 12, 12
Slide 17
Slide 17 text
Using Objects
var me = {
name : 'Ynon Perek',
email : '[email protected]',
web : 'http://ynonperek.com'
};
name Ynon Perek
email [email protected]
web http://ynonperek.com
Thursday, July 12, 12
Slide 18
Slide 18 text
Using Objects
console.dir(myObject); // prints all the fields
myObject.name === “Ynon Perek”
myObject[‘website’] === http://www.ynonperek.com
Thursday, July 12, 12
Slide 19
Slide 19 text
Object Patterns
Object Literals vs. Object Ctor
Maker functions
Object Prototypes
Thursday, July 12, 12
Slide 20
Slide 20 text
Object Literals vs. Ctor
Using object literals is the recommended way to
create objects
It is faster than calling new Object()
It is more predictable than calling new Object()
It is simpler
Thursday, July 12, 12
Slide 21
Slide 21 text
Maker Functions
Thursday, July 12, 12
Slide 22
Slide 22 text
Maker Functions
function Person(name, age) {
var that = { name : name, age : age };
that.hello = function() {
console.log(“Hello, My name is ” + that.name)
};
return that;
}
Thursday, July 12, 12
Slide 23
Slide 23 text
Maker Functions
Using a maker function to create new objects
saves duplicate code
Use the “that” pattern against “new” pitfalls
Load your newly created object with functions
Thursday, July 12, 12
Slide 24
Slide 24 text
Example
Implement a Quiz JavaScript system
Use “Question” class with four possible answers
and on correct answer
Use “Quiz” class to hold an array of questions
Thursday, July 12, 12
Slide 25
Slide 25 text
Object Prototypes
Thursday, July 12, 12
Slide 26
Slide 26 text
Object Prototypes
In JavaScript, every object has a “prototype”
object.
When JS interpreter fails to find an attribute in an
object, it searches the prototype.
Thursday, July 12, 12
Slide 27
Slide 27 text
Prototype Chain
Person
age : 12
Student
grade : 90
Freshman
goto: party
Worker
salary : 3800
Freshman.grade === 90 // from Student
Student.age === 12 // from Person
Worker.age === 12 // from Person
Worker.salary === 3800 // from Worker
Thursday, July 12, 12
Slide 28
Slide 28 text
The object Function
function object(parent) {
function F() {};
F.prototype = parent || Object;
return new F();
}
Thursday, July 12, 12
Slide 29
Slide 29 text
The object Function
creates a new object with the prototype ‘parent’
uses new to keep the prototype link
supports no arguments for object literals
Thursday, July 12, 12
Slide 30
Slide 30 text
Prototype Example
var person = { age : 12 };
var student = object(person);
student.grade = 90;
var freshman = object(student);
freshman.goto = “party”;
Thursday, July 12, 12
Slide 31
Slide 31 text
Prototypes & Makers
Always use Maker functions
For leafs, initialize object literals
For nodes, use the object() function
Thursday, July 12, 12
Slide 32
Slide 32 text
Exercise
Write a maker function for a Car object, using an
object literal. Car should provide members:
max_speed and drive()
Write maker functions for 3 car models using the
object() function.
Implement a function on a car model which uses
data from Car
Thursday, July 12, 12
Slide 33
Slide 33 text
Arrays
Arrays are objects with numeric keys.
A length attribute is maintained automatically by
JS to mean last_index + 1
Thursday, July 12, 12
Slide 34
Slide 34 text
Array Functions
join
pop, push
shift, unshift
reverse, sort - changes original array
a.slice(0, a.length).reverse() - Does not modify
original array a
Thursday, July 12, 12
Slide 35
Slide 35 text
Exercise
Implement a Phonebook object that maintains an
array of Contact objects.
Each Contact should have a name field and a
phone field.
Test by creating 5 contacts in the Phonebook and
print them to the console.
Thursday, July 12, 12
Slide 36
Slide 36 text
Q & A
JavaScript History
Language Overview
Arrays & Objects
Functions
Thursday, July 12, 12
Slide 37
Slide 37 text
Functions
The word ‘function’
Followed by an optional name
Followed by a set of parameters
Followed by the function body
Thursday, July 12, 12
Slide 38
Slide 38 text
Functions
function hello(who) {
console.log(“Hello, “ + who);
}
var hello = function hello(who) {
console.log(“Hello, “ + who);
};
Thursday, July 12, 12
Slide 39
Slide 39 text
Function.Prototype
Provides:
apply, call
toString
Thursday, July 12, 12
Slide 40
Slide 40 text
Scope
In JavaScript, only functions have scope.
The var keyword indicates a scoped variable
There is no block scope
Thursday, July 12, 12
Slide 41
Slide 41 text
Scope
// Using functions to scope our code
(function() {
var x = 5;
var y = 7;
console.log(x + y);
}());
Thursday, July 12, 12
Slide 42
Slide 42 text
Scope
Do:
Wrap every file in an anonymous function
Prefix every variable with var
A Good fence makes good neighbors
Thursday, July 12, 12
Slide 43
Slide 43 text
Constructor Functions
If a function is called with new:
A new object is created before entering the
function
That object is passed as the this argument
That object becomes the default return value of
the function
Function’s prototype is assigned to the object
Thursday, July 12, 12
Slide 44
Slide 44 text
Consturctor Functions
function Foo() { }
var p = {
name: 'Mike',
job: 'Musician'
};
Foo.prototype = p;
var p1 = new Foo();
var p2 = new Foo();
// Prints out mike
console.log( p1.name );
Thursday, July 12, 12
Slide 45
Slide 45 text
Return Value
return is used to return a value
default return value for non-ctor functions is
undefined
default return value for ctor is this
Thursday, July 12, 12
Slide 46
Slide 46 text
Tip
Prefer that-style constructor over this
In that-style constructors, always remember to
return that.
Thursday, July 12, 12
Slide 47
Slide 47 text
JavaScript
And The DOM
Thursday, July 12, 12
Slide 48
Slide 48 text
DOM Basics
DOM stands for
Document Object
Model
Every DOM element
has a corresponding
JS object
HTMLDivElement
HTML
div
JS
Thursday, July 12, 12
Slide 49
Slide 49 text
DOM Basics
Use
getElementById to
get specific element
Use querySelector
to get an element
using CSS selector
var t = document.getElementById('text');
t.innerHTML = "Hello World";
Thursday, July 12, 12
Slide 50
Slide 50 text
DOM Agenda
jQuery Introduction
Handling Events
Simple Web App
Thursday, July 12, 12
Slide 51
Slide 51 text
DOM Facts
Thursday, July 12, 12
Slide 52
Slide 52 text
DOM Facts
Every Browser is
different
Bright Side: Mobile
Thursday, July 12, 12
Slide 53
Slide 53 text
AJAX Libraries
Developer tools to
cover bad stuff from
developers
jQuery, YUI, Dojo,
ExtJS, ...
Thursday, July 12, 12
Slide 54
Slide 54 text
jQuery Selectors
Use $(‘...’) to select
elements
Get jQuery object !=
document.querySelect
or
$('p#text').html("Hello World");
Thursday, July 12, 12
Slide 55
Slide 55 text
jQuery Selectors
Use $(‘...’) to select
elements
Get jQuery object !=
document.querySelect
or
$('p#text').html("Hello World");
Selector returning a
jQuery Object
Thursday, July 12, 12
Slide 56
Slide 56 text
jQuery Selectors
Use $(‘...’) to select
elements
Get jQuery object !=
document.querySelect
or
$('p#text').html("Hello World");
An action to perform
on the object
Thursday, July 12, 12
Slide 57
Slide 57 text
Selectors Overview
ID Selectors
Class Selectors
Descendants Selectors
Thursday, July 12, 12
Slide 58
Slide 58 text
Class Selector
Selects all elements having a class attribute
img.thumb { width: 32px; height: 32px; }
CSS
HTML
Thursday, July 12, 12
Slide 59
Slide 59 text
Descendants Selector
Select all descendants of the given element
.gallery img { border: 2px solid blue; }
Nth Child
Dollar
USA
Pound
Great Britain
Yen
Japan
Euro
EMU
Dollar USA
Pound Great Britain
Yen Japan
Thursday, July 12, 12
Slide 62
Slide 62 text
Nth Child
An element that has an+b-1 siblings before in
the document tree
Very useful for zebra tables
Can save html classes: first, second, third, etc.
Thursday, July 12, 12
DEMO
Grid of four boxes
Click on the red to win
Thursday, July 12, 12
Slide 68
Slide 68 text
Q & A
Thursday, July 12, 12
Slide 69
Slide 69 text
jQuery Lab
Write a web application that splits the screen into
four sections. Each click on a section should
display a sentence inside the clicked section
Write a web app to convert time units. User should
enter time in seconds, minutes or hours, and
convert to all the others
Thursday, July 12, 12
Slide 70
Slide 70 text
Function Patterns
Modules
Immediate Functions
Configuration Objects
Prototype Methods
Thursday, July 12, 12
Slide 71
Slide 71 text
Modules
A module is a unit of code reuse
Some code in a module is “public” - shared with
other modules.
Some code in a module is “private” - cannot be
accessed from outside.
Thursday, July 12, 12
Slide 72
Slide 72 text
Function Arguments
function sum() {
var i = 0,
n = arguments.length,
sum = 0;
for ( i=0; i < n; ++i ) {
sum += arguments[i];
}
return sum;
}
Thursday, July 12, 12
Slide 73
Slide 73 text
Example - Calculator
Public code:
add_to_register
sub_from_register
read_register
zero_register
http://ynonperek.com/course/web/javascript-
functions.html#modules
Thursday, July 12, 12
Slide 74
Slide 74 text
Immediate Functions
Execute a function as soon as it is defined
Provides a scoped “sandbox” for initialization
code
Pass in the global object to avoid using ‘window’
in your code.
Thursday, July 12, 12
Slide 75
Slide 75 text
Configuration Objects
When a large list of arguments is required, use
configuration objects
Solves “which comes first”
Rule of Thumb: if params > 2, use the object
Thursday, July 12, 12
Slide 76
Slide 76 text
Configuration Objects
Example
Student function which takes a configuration
object with optional values
http://ynonperek.com/course/web/javascript-
functions.html#conf
Thursday, July 12, 12
Slide 77
Slide 77 text
Function Exercise
Write a module for time management
Module should provide:
add_meeting(meeting_info)
delete_meeting(meeting_info)
get_meetings_between(start_dt, end_dt)
Thursday, July 12, 12
Slide 78
Slide 78 text
Function Patterns
Modules
Immediate Functions
Configuration Objects
Prototype Methods
Thursday, July 12, 12
Slide 79
Slide 79 text
Function Prototypes
Thursday, July 12, 12
Slide 80
Slide 80 text
Function Prototypes
functions have a special attribute: prototype
When an object’s attribute lookup is performed,
the interpreter checks its constructor.prototype
Thursday, July 12, 12
Slide 81
Slide 81 text
Function Prototypes
We implement inheritance using prototypes - this
is called prototypical inheritance
Example: http://ynonperek.com/course/fed/
javascript-oo.html
Thursday, July 12, 12
Slide 82
Slide 82 text
Design Patterns
Singleton
Factory
Super
Thursday, July 12, 12
Slide 83
Slide 83 text
Singleton
Put the object on global.
Access it from everywhere in your program
Always consider using a namespace
global.Log = log;
Thursday, July 12, 12
Slide 84
Slide 84 text
Factory
Use a single factory object with a method to
produce each product
Implement a product method that takes a name of
a product, and runs its correct producer function
CarFactory.produce = function(model) {
var ctor = CarFactory[model];
return ctor();
}
Thursday, July 12, 12
Slide 85
Slide 85 text
Using Super
JavaScript has no native ‘super’ call
To use the superclass in the inheritance chain, we
must work something out ourselves
Let’s modify our object function to allow super
Thursday, July 12, 12
Slide 86
Slide 86 text
Using Super
function object(parent) {
function F() { /* CODE GOES HERE */ };
F.prototype = parent || Object;
return new F();
}
Thursday, July 12, 12
Slide 87
Slide 87 text
Using Super
function object(parent) {
function F() { this.uber = parent };
F.prototype = parent || Object;
return new F();
}
Thursday, July 12, 12
Slide 88
Slide 88 text
Using Super
Now each object has an ‘uber’ property that
points to its prototype object
Can use student.uber.age to get the person’s age
Thursday, July 12, 12
Slide 89
Slide 89 text
JS App Tips
App is made of components. On mobile, only one
visible component at a time; on Desktop, can have
more than one.
Each component has its own JS file
Different components can communicate using a
global object in a private namespace
A single controller object moves components in/
out of view
Thursday, July 12, 12
Slide 90
Slide 90 text
Q & A
Thursday, July 12, 12
Slide 91
Slide 91 text
Thank You
Ynon Perek
[email protected]
ynonperek.com
Thursday, July 12, 12