Misko Js Presentation

download Misko Js Presentation

of 25

Transcript of Misko Js Presentation

  • 8/9/2019 Misko Js Presentation

    1/25

    How JavaScript Works

    -- Miko Hevery

  • 8/9/2019 Misko Js Presentation

    2/25

    Basic Concepts

    Object === HashObject, Array, String, Number, Function, null, undefined

    JavaScript is a functional language

    Functions are first class citizensRole of Closures

    JavaScript does not define any OO notions

    Classes / InheritanceOO conventions

    Browser APIglobal window

  • 8/9/2019 Misko Js Presentation

    3/25

    Follow on your computer

    Open your favorite browser and follow along in the debuggerconsole (not possible in IE)

  • 8/9/2019 Misko Js Presentation

    4/25

    Object === Hash

    Everything is an object, and an object is just a hashmap

    var obj1 = new Object();

    var obj2 = {};

    typeof obj1 ==> "object"

    obj1 instanceof Object ==> true

    obj1.constructor ==> Object

    obj1.name = "JavaScript";

    obj1["name"] ==> "JavaScript"

  • 8/9/2019 Misko Js Presentation

    5/25

    Object prototype chains

    var vehicle = { powered: true };

    var volvo = { seats: 4 };

    volvo.seats ==> 4

    volvo.powered ==> undefined

    volvo.__proto__ = vehicle;

    volvo.powered ==> true

    volvo.powered = 'gasoline';

    volvo.powered ==> 'gasoline'

    vehicle.powered ==> true

    volvo.__proto__.powered ==> true

  • 8/9/2019 Misko Js Presentation

    6/25

    Defining Functions

    function add(a, b) { return a + b; }

    var negate = function(a) { return -a; };

    add(1, 2) ==> 3

    add.apply(null, [1, 2]) ==> 3

    add.call(null, 1, 2) ==> 3typeof add ==> 'function'

    add.name ==> 'add'

    add.length ==> 2

    negate.name ==> ''

    typeof add.apply ==> 'function'

    negate.constructor ==> Function

    var negate2 = new Function('a', 'return -a;');

  • 8/9/2019 Misko Js Presentation

    7/25

    Function Closure

    function greeter(salutation) {

    var counter = 0;

    var prefix = '. ' +salutation + ' ';

    return function(name) {

    counter ++;return counter + prefix + name + '!';

    };

    }

    var greet = greeter('Hello');

    greet('World') ==> '1. Hello World!'

    greet('World') ==> '2. Hello World!'

  • 8/9/2019 Misko Js Presentation

    8/25

    Creating a Class

    There is no standard "class" it is just a convention!var circle = {};

    circle.radius = 5;

    circle.area = function(){

    return this.radius * this.radius * Math.PI;};

    circle.area() ==> 78.5398

    var fn = circle.area;

    fn.call() ==> NaN;

    window.radius = 1;

    fn.call() ==> 3.1415

    fn.call(circle) ==> 78.5375

  • 8/9/2019 Misko Js Presentation

    9/25

    Separating instance from Class

    var Circle = {

    area: function(){

    return this.radius * this.radius * Math.PI;

    }

    };

    var instance = { radius:5 };

    instance.__proto__ = Circle;

    instance.area() ==> 78.5398

  • 8/9/2019 Misko Js Presentation

    10/25

    Constructor

    function Circle(radius) {

    this.radius = radius;

    this.area = function(){

    return this.radius * this.radius * Math.PI;

    };}

    var instance = {};

    Circle.call(instance, 5);

    instance.area() ==> 78.5398

    var instance2 = new Circle(5);

    instance2.area() ==> 78.5398

    instance instanceof Circle ==> false

    instance2 instanceof Circle ==> true

  • 8/9/2019 Misko Js Presentation

    11/25

    new Operator

    function Class(){}

    var instance1 = new Class();

    var instance2 = {};instance2.constructor = Class;

    instance2.__proto__ = Class.prototype;

    Class.apply(instance2);

    instance[1|2].constructor == Class

    instance[1|2].__proto__ == Class.prototype

    instance[1|2] instanceof Class == true

  • 8/9/2019 Misko Js Presentation

    12/25

    Function constructorprototype

    function Circle(radius) {

    this.radius = radius;

    }

    Circle.prototype.area = function() {

    return this.radius * this.radius * Math.PI;};

    var instance = new Circle(5);

    instance.area() ==> 78.5375

    instance.constructor == Circle

    instance.__proto__ == Circle.prototype

    instance instanceof Circle == true

  • 8/9/2019 Misko Js Presentation

    13/25

    Function binding problem

    function Greeter(s){this.salutation = s;}

    Greeter.prototype.greet = function(name){

    alert(this.salutation + name);

    }

    var greeter = new Greeter();var server = new Server();

    server.getUser(greeter.greet);

    // greet function called with wrong 'this'

    server.getUser(function(name){

    greeter.greet(name);

    });

  • 8/9/2019 Misko Js Presentation

    14/25

    Function Binding

    function bind(fnThis, fn) {

    return function(){

    return fn.apply(fnThis, arguments);

    };

    }

    server.getUser(bind(greeter, greeter.greet));

  • 8/9/2019 Misko Js Presentation

    15/25

    Extending Types

    var text = 'Hello';

    typeof text ==> 'string'

    text.__proto__ ==> String.prototype

    text.reverse ==> undefined

    String.prototype.reverse = function(){

    var text = '';

    for(var i=0; i < this.length; i++)

    text = this.charAt(i) + text;

    return text;

    }

    text.reverse() ==> 'olleH';

  • 8/9/2019 Misko Js Presentation

    16/25

    Array iteration

    var log = '';

    var array = ['car', 'book', 'table'];

    // ??? {length:3, 0:'car', 1:'book', 2:'table}

    for(var i=0; i < array.length; i++) {log += log[i] + ';';

    }

    log ==> 'car;book;table;'

    log = '';

    for(var i in array) {

    log += i + ':' + array[i] + ';';

    }

    log ==> '0:car;1:book;2:table;'

  • 8/9/2019 Misko Js Presentation

    17/25

    Object iteration

    var log = '';

    var spanish = {

    house:'casa',

    hello:'hola'

    };

    for(var key in spanish) {

    log += key + '=>' + spanish[key] + '; ';

    }

    log ==> 'house=>casa; hello=>hola; '

  • 8/9/2019 Misko Js Presentation

    18/25

    Global window

    var name = 'World';

    window.name ==> 'World';

    function greet(){

    var salutation = 'Hello';message = salutation + ' ' + name;

    }

    window.greet();

    window.salutation = undefined;

    window.message ==> 'Hello World';

  • 8/9/2019 Misko Js Presentation

    19/25

    Asynchronous API

    var xhr = ...;

    xhr.request('GET', '/url', function(data){

    alert(data);

    });

    // Pseudo Code

    while(true) {

    var event = waitForEvent();

    try{

    event();

    } catch(e) {}

    redrawDOM();

    }

  • 8/9/2019 Misko Js Presentation

    20/25

    DOM

    Parsed representation of the HTML is DOMChanging the DOM programatically changes the viewDOM is declarative

    var body = window.document.body;body.innerHTML = 'Hello World!';

    var person = body.getElementsByTagName('i')[0];

    person.textContent = 'Misko';

  • 8/9/2019 Misko Js Presentation

    21/25

    JavaScript Gotchas

    JavaScript OO by convention only

    Everything defaults to global 'window'

    No varimplies global 'window'

    Reference to a function losses 'this'

    defaults to 'window'

    Browser is single threaded and all calls return immediatelyit is impossible to wait for something, as that would blockthe UI thread

  • 8/9/2019 Misko Js Presentation

    22/25

    Browser Incompatibilities

    JavaScript is remarkably consistent across browsersIE: String [] does not work use .charAt()

    IE: Trailing list commas: [ 1, 2, ]

    IE: can not set__proto__

    Extended APIs

    DOM/CSS is remarkably inconsistent across browsersAPI to mutate DOM (solution: third-party-libraries)

    CSS to style DOM (no good solution)DOM: IE, WebKit, FireFox, OperaCSS: IE5, IE6, IE7, WebKit, FireFox, Opera

  • 8/9/2019 Misko Js Presentation

    23/25

    Browser Memory Leak

    JavaScript ObjectsSeparate memory heap / Advanced Garbage CollectorsCycles are not a problem

    DOM ObjectsC/C++ memory heap / RefCounting: malloc() & free()Cycles are problem for browser developers

    Memory Leakvar jsObject = { element: document.body };

    document.body.myAttribute = jsObject;

    document.addEventListener(...)

    Only problem for long lived AJAX apps (no page reloads)

  • 8/9/2019 Misko Js Presentation

    24/25

    Further Reading

    JavaScript puzzlershttp://ejohn.org/apps/learn/

    Reference

    http://www.w3schools.com/js/default.asphttp://www.w3schools.com/js/js_ex_dom.asp

    BOOK: JavaScript the good partshttp://www.crockford.com/javascript/

    Functional Programinghttp://eloquentjavascript.net/index.html

    http://www.crockford.com/javascript/http://www.w3schools.com/js/js_ex_dom.asphttp://www.w3schools.com/js/default.asphttp://ejohn.org/apps/learn/http://eloquentjavascript.net/index.htmlhttp://eloquentjavascript.net/chapter6.htmlhttp://www.crockford.com/javascript/http://www.w3schools.com/js/js_ex_dom.asphttp://www.w3schools.com/js/default.asphttp://ejohn.org/apps/learn/
  • 8/9/2019 Misko Js Presentation

    25/25

    JavaScript Libraries

    Browser DOM abstractionhttp://code.google.com/closure/http://jquery.com/

    Functional APIhttp://documentcloud.github.com/underscore/

    JavaScript on Serverhttp://nodejs.org/

    Better syntax for JavaScripthttp://jashkenas.github.com/coffee-script/

    http://nodejs.org/http://documentcloud.github.com/underscore/http://jquery.com/http://code.google.com/closure/http://jashkenas.github.com/coffee-script/http://nodejs.org/http://documentcloud.github.com/underscore/http://jquery.com/http://code.google.com/closure/