SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
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/

Más contenido relacionado

La actualidad más candente

JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into JavascriptMassimo Franciosa
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftOleksandr Stepanov
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Protocol in Swift
Protocol in SwiftProtocol in Swift
Protocol in SwiftYusuke Kita
 

La actualidad más candente (20)

JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Day 1
Day 1Day 1
Day 1
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in Swift
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile Services
 
Protocol in Swift
Protocol in SwiftProtocol in Swift
Protocol in Swift
 

Destacado

Information Security Lesson 7 - Remote Access - Eric Vanderburg
Information Security Lesson 7 - Remote Access - Eric VanderburgInformation Security Lesson 7 - Remote Access - Eric Vanderburg
Information Security Lesson 7 - Remote Access - Eric VanderburgEric Vanderburg
 
Adobe and Modern Web Development
Adobe and Modern Web DevelopmentAdobe and Modern Web Development
Adobe and Modern Web DevelopmentTerry Ryan
 
Personal Security Expo
Personal Security ExpoPersonal Security Expo
Personal Security Expojdspider
 
Beyond the Standards
Beyond the StandardsBeyond the Standards
Beyond the StandardsPaul Bakaus
 
JavaScript & Animation
JavaScript & AnimationJavaScript & Animation
JavaScript & AnimationCaesar Chi
 
Designing The Mobile User Experience
Designing The Mobile User ExperienceDesigning The Mobile User Experience
Designing The Mobile User ExperienceJose Alves
 
Java Script Animation
Java Script AnimationJava Script Animation
Java Script Animationrbiggs
 
Javascript Animation with Canvas - Gregory Starr 2015
Javascript Animation with Canvas - Gregory Starr 2015Javascript Animation with Canvas - Gregory Starr 2015
Javascript Animation with Canvas - Gregory Starr 2015Gregory Starr
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureSimon Willison
 
Introuction To jQuery
Introuction To jQueryIntrouction To jQuery
Introuction To jQueryWinster Lee
 

Destacado (12)

Information Security Lesson 7 - Remote Access - Eric Vanderburg
Information Security Lesson 7 - Remote Access - Eric VanderburgInformation Security Lesson 7 - Remote Access - Eric Vanderburg
Information Security Lesson 7 - Remote Access - Eric Vanderburg
 
Adobe and Modern Web Development
Adobe and Modern Web DevelopmentAdobe and Modern Web Development
Adobe and Modern Web Development
 
Personal Security Expo
Personal Security ExpoPersonal Security Expo
Personal Security Expo
 
Beyond the Standards
Beyond the StandardsBeyond the Standards
Beyond the Standards
 
Jquery
JqueryJquery
Jquery
 
JavaScript & Animation
JavaScript & AnimationJavaScript & Animation
JavaScript & Animation
 
Designing The Mobile User Experience
Designing The Mobile User ExperienceDesigning The Mobile User Experience
Designing The Mobile User Experience
 
Java Script Animation
Java Script AnimationJava Script Animation
Java Script Animation
 
Javascript Animation with Canvas - Gregory Starr 2015
Javascript Animation with Canvas - Gregory Starr 2015Javascript Animation with Canvas - Gregory Starr 2015
Javascript Animation with Canvas - Gregory Starr 2015
 
JavaScript Libraries: The Big Picture
JavaScript Libraries: The Big PictureJavaScript Libraries: The Big Picture
JavaScript Libraries: The Big Picture
 
Introuction To jQuery
Introuction To jQueryIntrouction To jQuery
Introuction To jQuery
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

Similar a JavaScript Core

HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webpjcozzi
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009tolmasky
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 

Similar a JavaScript Core (20)

Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 

Más de François Sarradin

Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016François Sarradin
 
Java8 eXperiment - Normandy JUG
Java8 eXperiment - Normandy JUGJava8 eXperiment - Normandy JUG
Java8 eXperiment - Normandy JUGFrançois Sarradin
 
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)François Sarradin
 

Más de François Sarradin (6)

Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016Java (8) eXperiments - DevoxxFR 2016
Java (8) eXperiments - DevoxxFR 2016
 
Java8 eXperiment - Normandy JUG
Java8 eXperiment - Normandy JUGJava8 eXperiment - Normandy JUG
Java8 eXperiment - Normandy JUG
 
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)
FLATMAP ZAT SHIT : les monades expliquées aux geeks (Devoxx France 2013)
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
Java 8 Lambda
Java 8 LambdaJava 8 Lambda
Java 8 Lambda
 
Programmation Fonctionnelle
Programmation FonctionnelleProgrammation Fonctionnelle
Programmation Fonctionnelle
 

JavaScript Core

  • 1. JavaScript Core Nicolas Demengel and François Sarradin
  • 2. Application (client side) 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. JavaScript Language & Concepts
  • 6. 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; }
  • 7. 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)
  • 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-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
  • 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 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);
  • 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 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
  • 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: 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
  • 22. Prototype-oriented programming Classes in JS? 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 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(); }; }
  • 25. 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";
  • 26. 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");
  • 27. 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
  • 28. 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); } /* ... */ }
  • 29. 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; } }; })();
  • 30. 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
  • 31. 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
  • 32. Access to Your Web Page DOM manipulation: tips ● know your CSS selectors ○ #element ○ .element ○ [attribute=value] ● limit changes to the DOM ○ use fragments
  • 33. The Good, The Bad, 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/