JavaScript Core

35
JavaScript Core Nicolas Demengel and François Sarradin

Transcript of JavaScript Core

Page 1: JavaScript Core

JavaScriptCore

Nicolas Demengel and François Sarradin

Page 2: JavaScript Core

JavaScript

HTLM(5)CSS(3)

Web PageAnimation

Application(client side)

JSEngine

Service(server side) Embeded

(noSql, ...)

ClientServer

Page 3: JavaScript Core

JavaScriptHistory

1995

Brendan Eich @ NetscapeJavaScript

1996

ECMA1.0, 1.1

1997

ECMAScript1.2

1998

1.3

2000

1.5ES 3

2010

1.8.5ES 5

What's next?

ES 6Harmony

Page 4: JavaScript Core

JavaScript

Self Python Perl C/Java

ActionScript CoffeeScriptDart

JavaScriptIs made of...

Page 5: JavaScript Core

JavaScript

Language&

Concepts

Page 6: JavaScript Core

/* Factorial of n. */function fact(n) { // result of fact var result = 1; for (var i = 1; i <= n; i++) { result *= i; } return result;}

JavaScript SyntaxLooks like Java / C++

Page 7: JavaScript Core

var x = 1; // it should be an intvar 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)

JavaScriptIs dynamically typed

Page 8: JavaScript Core

JavaScriptHas bad parts

42 == '42' !== 42if (false) <-> if (null) <-> if (undefined)false != null == undefinedfalse !== null !== undefined

return{

prop: "val"};

Use an editor providing validation with JSLint

Page 9: JavaScript Core

JavaScriptHas 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

Page 10: JavaScript Core

// function declaration (statement)function f(x) { /* ... */ }

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

// Function constructorvar f = new Function('x', '...');

JavaScriptCan define functions

Page 11: JavaScript Core

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);

JavaScriptCAN HAZ FUNCTIONZ EVERYWHERE

Page 12: JavaScript Core

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 methodfunction ln() { log(this.name); }var o = { name: "an object" };o.logName = ln;

JavaScriptFunction: scope & binding

Page 13: JavaScript Core

// what is the value of 'this'?var o = { /* ... */

logName: function() { log(this.name); }};

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

// what about the following?function ln() { log(this.name); }ln(); // er...

JavaScriptFunction: scope & binding

Page 14: JavaScript Core

● 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

JavaScriptFunction: scope & binding

Page 15: JavaScript Core

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!"

JavaScriptFunction: scope & binding

Page 16: JavaScript Core

(function(x, y) {console.log(y); > 'b'

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

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

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

})('a', 'b', 'c');

JavaScriptFunction arguments

Page 17: JavaScript Core

JVM

Prototype-oriented programmingLanguages

Self

Io

Ioke

NewtonScript JavaScript Lua

Page 18: JavaScript Core

var Vehicle = {description: "some vehicle",startEngine: function() {

console.log(this.description+ " => engine started");

}};// uses Vehicle as protovar Car = Object.create(Vehicle);Car.description = "some car";Car.wheelCount = 4;

Prototype-oriented programmingInstance, prototype, and inheritance

Page 19: JavaScript Core

Vehicle.startEngine();> "some vehicle => engine started"

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

console.log(Vehicle.wheelCount);> undefined

console.log(Car.wheelCount);> 4

Prototype-oriented programmingWhat do you get?

Page 20: JavaScript Core

Car.startEngine = function() {console.log("overridden");

}Car.startEngine(); > "overridden"

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

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

JS prototype-based programming= delegation (object ⇒ prototype)

Prototype-oriented programmingInheritance manipulation

Page 21: JavaScript Core

Car.startEngine = function() { Vehicle.startEngine.call(this); // ≃ super.start console.log("model: " + this.model);}

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

myPigeot.startEngine();// My Pigeot: engine started// model: 403

Prototype-oriented programmingInheritance: level 2

Page 22: JavaScript Core

Vehicle, Car = prototypes ≃ classes

Note: myPigeot can be prototype too!

Prototype-oriented programmingClasses in JS?

CarVehicule

myPigeot

Page 23: JavaScript Core

Wait!...

What about that Object.create()?

Prototype-oriented programming

Page 24: JavaScript Core

// Object.create(): JS 1.8.5 and +if (!Object.create) {

Object.create = function(o) {// creates new temp. constructorfunction F() {}

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

// instantiatesreturn new F();

};}

Prototype-oriented programmingCreate an instance

Page 25: JavaScript Core

// 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 programmingClasses in JS

Page 26: JavaScript Core

Er... Car is a functions, but I can new it?!

● new is a keyword that1. Allocates an object2. Inits this object with constructor

● new Car("some car") is equivalent tovar car = {};car.__proto__ = Car.prototype;Car.call(car, "some car");

Prototype-oriented programmingNew in JS

Page 27: JavaScript Core

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 programmingLast word about constructor functions

Page 28: JavaScript Core

● Be carefull with this and new

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

● Prevent bad usage of your constructorfunction Car(desc) {

if (!(this instanceof Car)) {return new Car(desc);

}/* ... */

}

Prototype-oriented programmingLast but not least

Page 29: JavaScript Core

var Entity = (function() { // class lvlvar counter = 0; // private

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

this.getId = function() {return id;

}};

})();

Prototype-oriented programmingPrivate members

Page 30: JavaScript Core

Prototype-oriented programmingPrivate members

var o1 = new Entity();var o2 = new Entity();

console.log(o1.id);> undefined

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

console.log(o2.getId());> 2

Page 31: JavaScript Core

Access to Your Web PageDOM manipulation

DOM != JS, it's another API

No need for jQuery○ getElementById()○ getElementByTagName()○ getElementByName()○ getElementByClassName() // !IE○ querySelector() // IE 8○ querySelectorAll() // IE 8

Page 32: JavaScript Core

Access to Your Web PageDOM manipulation: tips

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

● limit changes to the DOM○ use fragments

Page 33: JavaScript Core

The Good, The Bad, and The Ugly

Page 34: JavaScript Core

ReferencesBooks

David Flanagan, JavaScript: The Definitive Guide, 6th Edition, O'Reilly Media, April 2011

Doug Crockford, JavaScript: The Good Parts, O'Reilly Media, May 2008

Page 35: JavaScript Core

ReferencesOnline

Doug Crockford, JavaScript: The Good Partshttp://googlecode.blogspot.com/2009/03/doug-crockford-javascript-good-parts.html

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

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

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