KEMBAR78
JavaScript Core | PDF
JavaScript
             Core
Nicolas Demengel and François Sarradin
Application
  (client side)     Web Page
                    Animation


                                   HTLM(5)
                                   CSS(3)
Client
                  JavaScript               Server
           JS
         Engine


                      Service
                   (server side)    Embeded
                                    (noSql, ...)
JavaScript
 History

    1996     1998
 1995    1997     2000     2010    What's next?




    ECMA      1.3
   1.0, 1.1         1.5    1.8.5    ES 6
                    ES 3   ES 5    Harmony
      ECMAScript
Brendan Eich 1.2
@ Netscape
JavaScript
JavaScript
Is made of...

   Self     Python          Perl    C/Java



             JavaScript


   ActionScript      Dart      CoffeeScript
JavaScript

Language
   &
Concepts
JavaScript Syntax
Looks like Java / C++
/* Factorial of n. */
function fact(n) {
  // result of fact
  var result = 1;
  for (var i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}
JavaScript
Is dynamically typed
var x = 1; // it should be an int
var s = "a"; // string or char?

// it's a function, (type of p?
// does it return something?)
function f(p) { /* ... */ }

var g; // anything (even a function)
JavaScript
Has bad parts
42 == '42' !== 42
if (false) <-> if (null) <-> if (undefined)
false != null == undefined
false !== null !== undefined

return
{
   prop: "val"
};

Use an editor providing validation with JSLint
JavaScript
Has few built-in types
●   Boolean    true / false
●   Number     42 21.6 NaN           +∞    -∞
●   String     "hi" 'hello'
●   Date       java-like
●   Regexp     /^.*([0-9]+)w{2,3}$/
●   Object     {prop: val}
●   Array      [a, b]    (it's just an Object)
●   Function   function() {}

● List, Map, Set: where are you? => ES 6
JavaScript
Can define functions
// function declaration (statement)
function f(x) { /* ... */ }

// function expression (operator)
var f = function(x) { /* ... */ };

// Function constructor
var f = new Function('x', '...');
JavaScript
CAN HAZ FUNCTIONZ EVERYWHERE
function compose(f, g) {
  // BTW, this is a closure!
  // more on that later
  return function(x) {
     return f(g(x));
  };
}

compose(square, add_one)(10);
JavaScript
Function: scope & binding
var o = {
   name: "an object",
   logName: function() { log(this.name); }
};

// o.logName can be assigned to a variable:
var logN = o.logName;
logN();

// another way to give o the logName method
function ln() { log(this.name); }
var o = { name: "an object" };
o.logName = ln;
JavaScript
Function: scope & binding
// what is the value of 'this'?
var o = { /* ... */
   logName: function() { log(this.name); }
};

// here it obviously refers to o
o.logName();

// what about the following?
function ln() { log(this.name); }
ln(); // er...
JavaScript
Function: scope & binding
● this = object to wich the function is bound
  ○ By default: the global object (window in browsers)

● Change the way a function is bound to an
  object: apply or call
JavaScript
Function: scope & binding
var o = { nm: "John Doe" };

function say(message) {
  console.log(this.nm + ": " + message);
}

say("hello!"); // ": hello!" (this.nm is undefined)

o.sayIt = say;
o.sayIt("greetings!");   // "John Doe: greetings!"

say.call(o, "yo!");      // "John Doe: yo!"
say.apply(o, ["hi!"]);   // "John Doe: hi!"
JavaScript
Function arguments
(function(x, y) {
   console.log(y); > 'b'

  console.log(arguments.length); > 3
  console.log(arguments[2]); > 'c'

  console.log(arguments.callee);> function(){ }

  console.log(arguments.join); > undefined
  // Array.prototype.join.call(arguments)

})('a', 'b', 'c');
Prototype-oriented programming
Languages


                 Self

NewtonScript   JavaScript   Lua     Io


                                  Ioke
                                  JVM
Prototype-oriented programming
Instance, prototype, and inheritance
var Vehicle = {
   description: "some vehicle",
   startEngine: function() {
     console.log(this.description
           + " => engine started");
   }
};
// uses Vehicle as proto
var Car = Object.create(Vehicle);
Car.description = "some car";
Car.wheelCount = 4;
Prototype-oriented programming
What do you get?
Vehicle.startEngine();
> "some vehicle => engine started"

Car.startEngine();
> "some car => engine started"

console.log(Vehicle.wheelCount);
> undefined

console.log(Car.wheelCount);
> 4
Prototype-oriented programming
Inheritance manipulation
Car.startEngine = function() {
   console.log("overridden");
}
Car.startEngine(); > "overridden"

// let's delete the car-specific method
delete Car.startEngine;

// parent method is still there
Car.startEngine(); > "some car => engine started"

           JS prototype-based programming
            = delegation (object ⇒ prototype)
Prototype-oriented programming
Inheritance: level 2
Car.startEngine = function() {
  Vehicle.startEngine.call(this); // ≃ super.start
  console.log("model: " + this.model);
}

// inheritance is not limited to one level
var myPigeot = Object.create(Car);
myPigeot.description = "My Pigeot";
myPigeot.model = "403";

myPigeot.startEngine();
// My Pigeot: engine started
// model: 403
Prototype-oriented programming
Classes in JS?

    Vehicule
                           Car



                              myPigeot


Vehicle, Car = prototypes ≃ classes
Note: myPigeot can be prototype too!
Prototype-oriented programming




             Wait!...

   What about that Object.create()?
Prototype-oriented programming
Create an instance
// Object.create(): JS 1.8.5 and +
if (!Object.create) {
   Object.create = function(o) {
      // creates new temp. constructor
      function F() {}

         // gives it o as prototype
         F.prototype = o;

         // instantiates
         return new F();
    };
}
Prototype-oriented programming
Classes in JS
// previous example could have been written:
var Vehicle = { /* desc, startEngine */ };

function Car(desc) { this.description = desc; }

Car.prototype = Vehicle;

Car.prototype.description = "some car";
Car.prototype.wheelCount = 4;

var myPigeot = new Car("My Pigeot");
myPigeot.model = "403";
Prototype-oriented programming
New in JS
    Er... Car is a functions, but I can new it?!

● new is a keyword that
  1. Allocates an object
  2. Inits this object with constructor


●   new Car("some car") is equivalent to
      var car = {};
      car.__proto__ = Car.prototype;
      Car.call(car, "some car");
Prototype-oriented programming
Last word about constructor functions
What happens when calling the Car
constructor without new?

       this is bound to global object

Want to play this game?
  ○ Change window.location and you'll risk a crash
Prototype-oriented programming
Last but not least
● Be carefull with this and new

● Factory method instead of new
  function createCar(d) { return new Car(d); }

● Prevent bad usage of your constructor
  function Car(desc) {
     if (!(this instanceof Car)) {
        return new Car(desc);
     }
     /* ... */
  }
Prototype-oriented programming
Private members
var Entity = (function() { // class lvl
   var counter = 0;        // private

  return function() {      // instance lvl
    var id = counter++;    // private

     this.getId = function() {
       return id;
     }
   };
})();
Prototype-oriented programming
Private members
var o1 = new Entity();
var o2 = new Entity();

console.log(o1.id);
> undefined

console.log(o1.getId());
> 1

console.log(o2.getId());
> 2
Access to Your Web Page
DOM manipulation
DOM != JS, it's another API

No need for jQuery
  ○   getElementById()
  ○   getElementByTagName()
  ○   getElementByName()
  ○   getElementByClassName()   // !IE
  ○   querySelector()             // IE 8
  ○   querySelectorAll()        // IE 8
Access to Your Web Page
DOM manipulation: tips

● know your CSS selectors
  ○ #element
  ○ .element
  ○ [attribute=value]


● limit changes to the DOM
  ○ use fragments
The Good, The Bad, and The Ugly
References
Books
David Flanagan, JavaScript: The Definitive Guide, 6th
Edition, O'Reilly Media, April 2011

Doug Crockford, JavaScript: The Good Parts, O'Reilly
Media, May 2008
References
Online
Doug Crockford, JavaScript: The Good Parts
http://googlecode.blogspot.com/2009/03/doug-crockford-
javascript-good-parts.html

Alex Russel, Learning to Love JavaScript
http://www.google.com/events/io/2011/sessions/learning-to-
love-javascript.html

John Resig, Learning Advanced JavaScript
http://ejohn.org/apps/learn/

Mozilla, JavaScript Reference
https://developer.mozilla.org/en/JavaScript/Reference/

JavaScript Core

  • 1.
    JavaScript Core Nicolas Demengel and François Sarradin
  • 2.
    Application (clientside) Web Page Animation HTLM(5) CSS(3) Client JavaScript Server JS Engine Service (server side) Embeded (noSql, ...)
  • 3.
    JavaScript History 1996 1998 1995 1997 2000 2010 What's next? ECMA 1.3 1.0, 1.1 1.5 1.8.5 ES 6 ES 3 ES 5 Harmony ECMAScript Brendan Eich 1.2 @ Netscape JavaScript
  • 4.
    JavaScript Is made of... Self Python Perl C/Java JavaScript ActionScript Dart CoffeeScript
  • 5.
  • 6.
    JavaScript Syntax Looks likeJava / C++ /* Factorial of n. */ function fact(n) { // result of fact var result = 1; for (var i = 1; i <= n; i++) { result *= i; } return result; }
  • 7.
    JavaScript Is dynamically typed varx = 1; // it should be an int var s = "a"; // string or char? // it's a function, (type of p? // does it return something?) function f(p) { /* ... */ } var g; // anything (even a function)
  • 8.
    JavaScript Has bad parts 42== '42' !== 42 if (false) <-> if (null) <-> if (undefined) false != null == undefined false !== null !== undefined return { prop: "val" }; Use an editor providing validation with JSLint
  • 9.
    JavaScript Has few built-intypes ● Boolean true / false ● Number 42 21.6 NaN +∞ -∞ ● String "hi" 'hello' ● Date java-like ● Regexp /^.*([0-9]+)w{2,3}$/ ● Object {prop: val} ● Array [a, b] (it's just an Object) ● Function function() {} ● List, Map, Set: where are you? => ES 6
  • 10.
    JavaScript Can define functions //function declaration (statement) function f(x) { /* ... */ } // function expression (operator) var f = function(x) { /* ... */ }; // Function constructor var f = new Function('x', '...');
  • 11.
    JavaScript CAN HAZ FUNCTIONZEVERYWHERE function compose(f, g) { // BTW, this is a closure! // more on that later return function(x) { return f(g(x)); }; } compose(square, add_one)(10);
  • 12.
    JavaScript Function: scope &binding var o = { name: "an object", logName: function() { log(this.name); } }; // o.logName can be assigned to a variable: var logN = o.logName; logN(); // another way to give o the logName method function ln() { log(this.name); } var o = { name: "an object" }; o.logName = ln;
  • 13.
    JavaScript Function: scope &binding // what is the value of 'this'? var o = { /* ... */ logName: function() { log(this.name); } }; // here it obviously refers to o o.logName(); // what about the following? function ln() { log(this.name); } ln(); // er...
  • 14.
    JavaScript Function: scope &binding ● this = object to wich the function is bound ○ By default: the global object (window in browsers) ● Change the way a function is bound to an object: apply or call
  • 15.
    JavaScript Function: scope &binding var o = { nm: "John Doe" }; function say(message) { console.log(this.nm + ": " + message); } say("hello!"); // ": hello!" (this.nm is undefined) o.sayIt = say; o.sayIt("greetings!"); // "John Doe: greetings!" say.call(o, "yo!"); // "John Doe: yo!" say.apply(o, ["hi!"]); // "John Doe: hi!"
  • 16.
    JavaScript Function arguments (function(x, y){ console.log(y); > 'b' console.log(arguments.length); > 3 console.log(arguments[2]); > 'c' console.log(arguments.callee);> function(){ } console.log(arguments.join); > undefined // Array.prototype.join.call(arguments) })('a', 'b', 'c');
  • 17.
    Prototype-oriented programming Languages Self NewtonScript JavaScript Lua Io Ioke JVM
  • 18.
    Prototype-oriented programming Instance, prototype,and inheritance var Vehicle = { description: "some vehicle", startEngine: function() { console.log(this.description + " => engine started"); } }; // uses Vehicle as proto var Car = Object.create(Vehicle); Car.description = "some car"; Car.wheelCount = 4;
  • 19.
    Prototype-oriented programming What doyou get? Vehicle.startEngine(); > "some vehicle => engine started" Car.startEngine(); > "some car => engine started" console.log(Vehicle.wheelCount); > undefined console.log(Car.wheelCount); > 4
  • 20.
    Prototype-oriented programming Inheritance manipulation Car.startEngine= function() { console.log("overridden"); } Car.startEngine(); > "overridden" // let's delete the car-specific method delete Car.startEngine; // parent method is still there Car.startEngine(); > "some car => engine started" JS prototype-based programming = delegation (object ⇒ prototype)
  • 21.
    Prototype-oriented programming Inheritance: level2 Car.startEngine = function() { Vehicle.startEngine.call(this); // ≃ super.start console.log("model: " + this.model); } // inheritance is not limited to one level var myPigeot = Object.create(Car); myPigeot.description = "My Pigeot"; myPigeot.model = "403"; myPigeot.startEngine(); // My Pigeot: engine started // model: 403
  • 22.
    Prototype-oriented programming Classes inJS? Vehicule Car myPigeot Vehicle, Car = prototypes ≃ classes Note: myPigeot can be prototype too!
  • 23.
    Prototype-oriented programming Wait!... What about that Object.create()?
  • 24.
    Prototype-oriented programming Create aninstance // Object.create(): JS 1.8.5 and + if (!Object.create) { Object.create = function(o) { // creates new temp. constructor function F() {} // gives it o as prototype F.prototype = o; // instantiates return new F(); }; }
  • 25.
    Prototype-oriented programming Classes inJS // previous example could have been written: var Vehicle = { /* desc, startEngine */ }; function Car(desc) { this.description = desc; } Car.prototype = Vehicle; Car.prototype.description = "some car"; Car.prototype.wheelCount = 4; var myPigeot = new Car("My Pigeot"); myPigeot.model = "403";
  • 26.
    Prototype-oriented programming New inJS Er... Car is a functions, but I can new it?! ● new is a keyword that 1. Allocates an object 2. Inits this object with constructor ● new Car("some car") is equivalent to var car = {}; car.__proto__ = Car.prototype; Car.call(car, "some car");
  • 27.
    Prototype-oriented programming Last wordabout constructor functions What happens when calling the Car constructor without new? this is bound to global object Want to play this game? ○ Change window.location and you'll risk a crash
  • 28.
    Prototype-oriented programming Last butnot least ● Be carefull with this and new ● Factory method instead of new function createCar(d) { return new Car(d); } ● Prevent bad usage of your constructor function Car(desc) { if (!(this instanceof Car)) { return new Car(desc); } /* ... */ }
  • 29.
    Prototype-oriented programming Private members varEntity = (function() { // class lvl var counter = 0; // private return function() { // instance lvl var id = counter++; // private this.getId = function() { return id; } }; })();
  • 30.
    Prototype-oriented programming Private members varo1 = new Entity(); var o2 = new Entity(); console.log(o1.id); > undefined console.log(o1.getId()); > 1 console.log(o2.getId()); > 2
  • 31.
    Access to YourWeb Page DOM manipulation DOM != JS, it's another API No need for jQuery ○ getElementById() ○ getElementByTagName() ○ getElementByName() ○ getElementByClassName() // !IE ○ querySelector() // IE 8 ○ querySelectorAll() // IE 8
  • 32.
    Access to YourWeb Page DOM manipulation: tips ● know your CSS selectors ○ #element ○ .element ○ [attribute=value] ● limit changes to the DOM ○ use fragments
  • 33.
    The Good, TheBad, and The Ugly
  • 34.
    References Books David Flanagan, JavaScript:The Definitive Guide, 6th Edition, O'Reilly Media, April 2011 Doug Crockford, JavaScript: The Good Parts, O'Reilly Media, May 2008
  • 35.
    References Online Doug Crockford, JavaScript:The Good Parts http://googlecode.blogspot.com/2009/03/doug-crockford- javascript-good-parts.html Alex Russel, Learning to Love JavaScript http://www.google.com/events/io/2011/sessions/learning-to- love-javascript.html John Resig, Learning Advanced JavaScript http://ejohn.org/apps/learn/ Mozilla, JavaScript Reference https://developer.mozilla.org/en/JavaScript/Reference/