intro to advanced javascript

111
Intro to Advanced JavaScript By Ryan Stout

Upload: ryanstout

Post on 05-Dec-2014

1.669 views

Category:

Technology


2 download

DESCRIPTION

Slides from my JS presentation I gave to the Montana Programmers meetup on 12/15/10

TRANSCRIPT

Page 1: Intro to Advanced JavaScript

Intro to Advanced JavaScript

By Ryan Stout

Page 2: Intro to Advanced JavaScript

About Me

Page 3: Intro to Advanced JavaScript

Ryan Stout

agileproductions.com github.com/ryanstout

Page 4: Intro to Advanced JavaScript

Programming JavaScript for

14 Years

Page 5: Intro to Advanced JavaScript

ExceptionHub

Page 6: Intro to Advanced JavaScript

JavaScript History

Page 7: Intro to Advanced JavaScript

JavaScript History

Developed by Brendan Eich in 1995

Page 8: Intro to Advanced JavaScript

JavaScript History

Originally called Mocha, then LiveScript

Page 9: Intro to Advanced JavaScript

JavaScript History

Inspired By Scheme and Self

Page 10: Intro to Advanced JavaScript

JavaScript History

Used C/Java Syntax

Page 11: Intro to Advanced JavaScript

JavaScript History

Renamed JavaScript to Play off Java

Page 12: Intro to Advanced JavaScript

JS Funnot really a number

typeof NaN//=> number

Page 14: Intro to Advanced JavaScript

TopicsConcepts

Page 15: Intro to Advanced JavaScript

TopicsFrameworks

Page 16: Intro to Advanced JavaScript

TopicsTools/Debugging

Page 17: Intro to Advanced JavaScript

TopicsTesting

Page 18: Intro to Advanced JavaScript

Concepts

Page 19: Intro to Advanced JavaScript

Types

Page 20: Intro to Advanced JavaScript

Primitivesvar myFloat = 5;var myFloat2 = 5.0;var myString = 'String';var myBoolean = true;var myNull = null;var myUndefined = undefined;

Page 21: Intro to Advanced JavaScript

Wrappersvar wFloat = new Number(42.0);var wString = new String('Hello');var wBoolean = new Boolean(true);

Page 22: Intro to Advanced JavaScript

Container Types

// Wrong Syntaxvar myArray = new Array();var myObject = new Object();

// Correct Syntaxvar myArray = [];var myObject = {};

Page 23: Intro to Advanced JavaScript

Dynamic Typing

var pies = 3;

alert("We have " + pies + " pies");// We have 3 pies

Page 24: Intro to Advanced JavaScript

Dynamic Typing

var pies = '5';

// eat 2pies = pies - 2;

alert('you have '+pies+' pies');// you have 3 pies

Page 25: Intro to Advanced JavaScript

Dynamic Typing

var pies = '5';

// bake 4pies = pies + 4;

alert('you have '+pies+' pies');// you have 54 pies

Page 26: Intro to Advanced JavaScript

JS Funmagically changing number

var a = 9999999999999999console.log(a);//=> 10000000000000000

Page 27: Intro to Advanced JavaScript

Objectsvar stateCapitals = {};stateCapitals['Oregon'] = 'Salem';stateCapitals['Montana'] = 'Helena';

stateCapitals['Montana']; // Helena

Page 28: Intro to Advanced JavaScript

Objectsvar stateCapitals = {};stateCapitals.Oregon = 'Salem';stateCapitals.Montana = 'Helena';

stateCapitals.Montana; // Helena

Page 29: Intro to Advanced JavaScript

Objectsvar stateCapitals = { 'Oregon': 'Salem', 'Montana': 'Helena'};

stateCapitals['Montana']; // HelenastateCapitals.Montana; // Helena

Page 30: Intro to Advanced JavaScript

Objects (Hash Buckets)

var states = new Number(50);states.Oregon = 'Salem';states.Montana = 'Helena';

states.Montana; // Helenaconsole.log("We have "+states+" states");// We have 50 states

Page 31: Intro to Advanced JavaScript

Object Iteration// Object Iterationfor (var state in states) { console.log(states[state] + ' is the\ capital of ' + state);}// Helena is the capital of Montana// ...

Page 32: Intro to Advanced JavaScript

Object Iteration// Object Iterationfor (var state in states) { if (states.hasOwnProperty(state)) { console.log(states[state] + ' is the\ capital of ' + state); }}// Helena is the capital of Montana

Page 33: Intro to Advanced JavaScript

Functions•First Class

•Lexical Scope

•Prototypal

•Closure

Page 34: Intro to Advanced JavaScript

MethodsMethods are just functions that are assigned to the property of an object.

Page 35: Intro to Advanced JavaScript

Functionsfunction concat(stringsArray) { return stringsArray.join('');}

concat(['Cat', 'Fish']); // CatFish

Page 36: Intro to Advanced JavaScript

First Classvar concat = function(stringsArray) { return stringsArray.join('');}

concat(['Cat', 'Fish']); // CatFish

Page 37: Intro to Advanced JavaScript

FunctionssayHi(); // hi

function sayHi() { console.log('hi');}

sayHi(); // hi

Page 38: Intro to Advanced JavaScript

First ClasssayHi(); // ReferenceError: sayHi is // not defined

var sayHi = function() { console.log('hi');}

sayHi(); // hi

Page 39: Intro to Advanced JavaScript

Lexical Scopefunction saySomething() { var message = 'Lexical Scoped'; console.log(message);}

saySomething(); // Lexical Scopedconsole.log(message); // ReferenceError: message is not defined

Page 40: Intro to Advanced JavaScript

Lexical Scopefunction sayDirection(up) { if (up == true) { var direction = 'up'; } else { var direction = 'down'; } console.log(direction);}sayDirection(true); // upsayDirection(false); // down

Page 41: Intro to Advanced JavaScript

Methodsvar Singleton = { setCount: function(count) { this.count = count; }, increment: function() { this.count++; }};

Singleton.setCount(5);Singleton.count; // 5Singleton.increment();Singleton.count;// 6

Page 42: Intro to Advanced JavaScript

ClosuresA "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Page 43: Intro to Advanced JavaScript

Closuresfunction makeAdder(aNum) { var addNumFunc = function(bNum) { return aNum + bNum; }; return addNumFunc;}

var addFive = makeAdder(5);console.log(addFive(2)); // 7console.log(addFive(10)); // 15

Page 44: Intro to Advanced JavaScript

$(function() { var links = $('a'); // loop through each link links.each( function(link, index) { // bind the click event $(link).click( function(event) { console.log('clicked link #'+index +' of ' + links.length); } ); } );});

Page 45: Intro to Advanced JavaScript

$(function() { var links = $('a'); // loop through each link links.each( function(link, index) { // bind the click event $(link).click( function(event) { console.log('clicked link #'+index +' of ' + links.length); } ); } );});

Page 46: Intro to Advanced JavaScript

$(function() { var links = $('a'); // loop through each link links.each( function(link, index) { // bind the click event $(link).click( function(event) { console.log('clicked link #'+index +' of ' + links.length); } ); } );});

Page 47: Intro to Advanced JavaScript

$(function() { var links = $('a'); // loop through each link links.each( function(link, index) { // bind the click event $(link).click( function(event) { console.log('clicked link #'+index +' of ' + links.length); } ); } );});

Page 48: Intro to Advanced JavaScript

$(function() { var links = $('a'); // loop through each link links.each( function(link, index) { // bind the click event $(link).click( function(event) { console.log('clicked link #'+index +' of ' + links.length); } ); } );});

Page 49: Intro to Advanced JavaScript

Closuresfunction addLinks() { for (var i=0, link; i<5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function () { console.log(i); }; document.body.appendChild(link); }}window.onload = addLinks;

Page 50: Intro to Advanced JavaScript

Closuresfunction addLinks() { for (var i=0, link; i<5; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (num) { return function () { alert(num); }; }(i); document.body.appendChild(link); }}

Page 51: Intro to Advanced JavaScript

Private Variablesvar person = function () { // Private var name = "Ryan"; return { getName : function () { return name; }, setName : function (newName) { name = newName; } };}();alert(person.name); // Undefinedalert(person.getName()); // "Ryan"person.setName("Brendan Eich");alert(person.getName()); // "Brendan Eich"

Page 52: Intro to Advanced JavaScript

Prototyping __proto__var states = { 'Montana': 'Helena', 'Oregon': 'Salem'};

var statesAndOthers = { 'Guam': 'Hagatna', 'Puerto Rico': 'San Juan'}

statesAndOthers['__proto__'] = states;statesAndOthers['Montana']; // HelenastatesAndOthers['Puerto Rico']; // San Juan

Page 53: Intro to Advanced JavaScript

Prototyping __proto_

statesAndOthersstatesAndOthersGuam HagatnaPuerto Rico

San Juan

__proto__

statesstatesMontana Helena

Oregon Salem

__proto__

Object

Page 54: Intro to Advanced JavaScript

One Problemvar states = { 'Montana': 'Helena' 'Oregon': 'Salem'};

var statesAndOthers = { 'Guam': 'Hagatna', 'Puerto Rico': 'San Juan'}

statesAndOthers['__proto__'] = states;statesAndOthers['Montana']; // HelenastatesAndOthers['Puerto Rico']; // San Juan

Page 55: Intro to Advanced JavaScript

Prototypingfunction extendedObject(o) { var objFunc = function() {}; objFunc.prototype = o; return new objFunc();}

var states = { 'Montana': 'Helena', 'Oregon': 'Salem'};

var statesAndOthers = extendedObject(states);statesAndOthers['Guam'] = 'Hagatna';statesAndOthers['Puerto Rico'] = 'San Juan';

statesAndOthers['Guam']; // HagantanstatesAndOthers['Montana']; // Helena

Page 56: Intro to Advanced JavaScript

Prototyping// Constructorfunction Animal(name) { this.name = name;}

Animal.prototype.speak = function() { console.log("Hi, I'm " + this.name);};

Animal.prototype.isAlive = function() { return true;};

var bob = new Animal('Bob');bob.speak(); // Hi, I'm Bobbob.isAlive(); // true

Page 57: Intro to Advanced JavaScript

Prototyping// Constructorfunction Animal(name) { this.name = name;}

Animal.prototype = { speak: function() { console.log("Hi, I'm " + this.name); },

isAlive: function() { return true; }};

var bob = new Animal('Bob');

Page 58: Intro to Advanced JavaScript

Animal Function Setup

Animal (func)Animal (func)prototype

Animal.prototypeAnimal.prototypeSpeak func

isAlive func

__proto__

Object

Page 59: Intro to Advanced JavaScript

Animal Instance Bob

bobbobname Bob

__proto__constructor Animal

Animal.prototypeAnimal.prototypeSpeak func

isAlive func

__proto__

Object

Page 60: Intro to Advanced JavaScript

Prototyping// Constructorfunction Dog(name) { this.name = name;}

Dog.prototype = new Animal();

Dog.prototype.speak = function() { console.log("Bark");};

Dog.prototype.rollOver = function() { console.log('rolling over...');};

var rover = new Dog('Rover');rover.speak(); // Barkrover.isAlive(); // true

Page 61: Intro to Advanced JavaScript

Dog Class

Animal.prototypeAnimal.prototypeSpeak func

isAlive func

__proto__

Object

Dog (func)Dog (func)prototype

prototype (Dog)prototype (Dog)name undefSpeak func

rollOver func

__proto__

Page 62: Intro to Advanced JavaScript

Rover

Animal.prototypeAnimal.prototypeSpeak func

isAlive func

__proto__

Object

roverrovername Rover

__proto__

Dog.prototypeDog.prototype(from new Animal())(from new Animal())

name undefSpeak func

rollOver func__proto__

Page 63: Intro to Advanced JavaScript

this

Page 64: Intro to Advanced JavaScript

Calling from thisvar EventTracker = {

count: 0, sayCount: function() { console.log(this.count, ' times'); }, track: function() { this.count += 1; this.sayCount(); }};

EventTracker.track(); // 1 timesEventTracker.track(); // 2 times

Page 65: Intro to Advanced JavaScript

More Closurevar EventTracker = {

count: 0, track: function() { var that = this; $.get('/track', function(data) { that.count += 1; console.log(that.count, ' times'); }); }};

Page 66: Intro to Advanced JavaScript

Setting thisvar obj1 = {

name: 'Object 1' sayName: function(before, after) { console.log(before + this.name + after); }};

var obj2 = { name: 'Object 2'};

obj1.sayName('hi ', '.'); // hi Object1.obj1.sayName.call(obj2, 'hi', '.'); // hi Object2obj1.sayName.apply(obj2, ['hi', '.']); // hi Object2

Page 67: Intro to Advanced JavaScript

More Closurevar EventTracker = {

count: 0, callBack: function(data) { this.count += 1; console.log(this.count, ' times'); }, track: function() { var that = this; $.get('/track', function() { that.callBack() }); }};

Page 68: Intro to Advanced JavaScript

More Closurevar EventTracker = {

count: 0, callBack: function(data) { this.count += 1; console.log(this.count, ' times'); }, track: function() { var that = this; $.get('/track', this.callback.bind(this)); }};

Page 69: Intro to Advanced JavaScript

Bind Functionif (!Function.prototype.bind) {

Function.prototype.bind = function(scope) { var func = this;

return function() { return func.apply(scope, arguments); }; };}

Page 70: Intro to Advanced JavaScript

JS Funlength of what

console.log((!+[]+[]+![]).length);//=> 9

Page 72: Intro to Advanced JavaScript

Compression

Page 73: Intro to Advanced JavaScript

CompressionJSMin

Page 74: Intro to Advanced JavaScript

CompressionYahoo Compressor

Page 75: Intro to Advanced JavaScript

CompressionGoogle Compressor

Page 76: Intro to Advanced JavaScript

Debugging

Page 77: Intro to Advanced JavaScript

Firebug - Console

Page 78: Intro to Advanced JavaScript

Firebug - HTML

Page 79: Intro to Advanced JavaScript

Firebug - CSS

Page 80: Intro to Advanced JavaScript

Firebug - Script

Page 81: Intro to Advanced JavaScript

Firebug - DOM

Page 82: Intro to Advanced JavaScript

Firebug - Net

Page 83: Intro to Advanced JavaScript

Google Chrome

Page 84: Intro to Advanced JavaScript

Safari

Page 85: Intro to Advanced JavaScript

Opera Dragonfly

Page 86: Intro to Advanced JavaScript

IE - Developer Toolbar

Page 87: Intro to Advanced JavaScript

Other IE Tools

Visual StudioMicrosoft Script Editor (Office)Microsoft Script Debugger (Free)

Page 88: Intro to Advanced JavaScript

Testing

http://stopbuyingrotas.wordpress.com/2008/10/

Page 89: Intro to Advanced JavaScript

JSpecR.I.P.

Page 90: Intro to Advanced JavaScript

JasmineThe New Hotness

http://pivotal.github.com/jasmine/

Page 91: Intro to Advanced JavaScript

JasmineBehavior Driven DevelopmentRuns in the BrowserRuby Gem to Automate Tests

Page 92: Intro to Advanced JavaScript

Jasminedescribe("javascript", function() { it('should increment a variable', function () { var foo = 0; foo++;

expect(foo).toEqual(1); });});

Page 93: Intro to Advanced JavaScript

Jasminedescribe("spy behavior", function() { it('should spy on an instance method', function() { var obj = new Klass(); spyOn(obj, 'method'); obj.method('foo argument');

expect(obj.method).toHaveBeenCalledWith('foo \ argument');

var obj2 = new Klass(); spyOn(obj2, 'method'); expect(obj2.method).not.toHaveBeenCalled(); });});

Page 94: Intro to Advanced JavaScript

JS Funbad math

console.log(0.1 + 0.2)//=> 0.30000000000000004

Page 96: Intro to Advanced JavaScript

Frameworks

The bad news is JavaScript is broken, the good news is we can fix it with JavaScript

- anonymous

Page 97: Intro to Advanced JavaScript

JQuey

• DOM Wrapper

• Event Binding

• Ajax (XMLHttpRequest)

Page 98: Intro to Advanced JavaScript

Underscore.jsList comprehension library

Page 99: Intro to Advanced JavaScript

Underscore.js

_.map([1, 2, 3], function(n){ return n * 2; });_([1, 2, 3]).map(function(n){ return n * 2; });// [2, 4, 6]

Map

Page 100: Intro to Advanced JavaScript

Underscore.js

_.each([1, 2, 3], function(num) { alert(num); });// alerts each number in turn..._.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });// alerts each number in turn...

Each

Page 101: Intro to Advanced JavaScript

Underscore.js

_.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0;});=> [1, 3, 5]

Reject

Page 102: Intro to Advanced JavaScript

Underscore.js• Also

• include, any, max, min, first, select, indexOf, etc...

• very useful

Page 103: Intro to Advanced JavaScript

Reading

Page 104: Intro to Advanced JavaScript

One More Thing

http://www.flickr.com/photos/swarmoeskerken/3382771943/sizes/l/

CoffeeScript

Page 105: Intro to Advanced JavaScript

CoffeeScript# Assignment:number = 42opposite = true

# Conditions:number = -42 if opposite

# Functions:square = (x) -> x * x

# Arrays:list = [1, 2, 3, 4, 5]

var list, number, opposite, square;

number = 42;opposite = true;if (opposite) { number = -42;}square = function(x) { return x * x;};list = [1, 2, 3, 4, 5];

Page 106: Intro to Advanced JavaScript

CoffeeScript# Objects:math = root: Math.sqrt square: square cube: (x) -> x * square x

var square;math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); }};

Page 107: Intro to Advanced JavaScript

CoffeeScript

# Splats:race = (winner, runners...) -> print winner, runners

# Existence:alert "I knew it!" if elvis?

race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners);};if (typeof elvis != "undefined" && elvis !== null) { alert("I knew it!");}

Page 108: Intro to Advanced JavaScript

CoffeeScript# Array comprehensions:cubes = (math.cube num for num in list)

cubes = (function() { _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results;}());

Page 109: Intro to Advanced JavaScript

JS Funconfused >

3 > 2 > 1 // false

Page 110: Intro to Advanced JavaScript

Questions

agileproductions.com

[email protected]