Upload
dhaval10690
View
136
Download
0
Embed Size (px)
Citation preview
2
Agenda
Introduction to ES6 Features of ES6 Usage of ES6 Introduction to AMD Usage of Require with Angular Demo Q&A
5
Introduction ES6
The next major version of JavaScript
Modular Much readable Lesser Code More control
7
ConstantsES6 const PI = 3.141593
PI > 3.0
ES5Object.defineProperty(typeof global === "object" ? global : window, "PI", {
value: 3.141593,enumerable: true, writable: false, configurable: false
}) PI > 3.0;
Problem with ES5
• ES5 constants works only on global context not in a block scope
9
Blocked-scoped variables without hoisting
ES6 for (let i = 0; i < a.length; i++) { let x = a[i] …
} for (let i = 0; i < b.length; i++) {
let y = b[i] …
}
ES5 var i, x, y; for (i = 0; i < a.length; i++) {
x = a[i]; …
} for (i = 0; i < b.length; i++){
y = b[i]; …
}
10
Blocked-scoped variables with hoisting
ES6 let callbacks = []for (let i = 0; i <= 1; i++) {
callbacks[i] = function () { return i * 2
} } callbacks[0]() === 0 callbacks[1]() === 2
ES5 var callbacks = []; for (var i = 0; i <= 1; i++) {
(function (i) { callbacks[i] = function() {
return i * 2; };
})(i); } callbacks[0]() === 0; callbacks[1]() === 2;
11
Blocked-scoped Function
ES6 { function foo () { return 1 } foo() === 1 {
function foo () { return 2 } foo() === 2
} foo() === 1
}
ES5 (function () { var foo = function () { return 1; } foo() === 1; (function () {
var foo = function () { return 2; } foo() === 2;
})(); foo() === 1;
})();
13
Expression Bodies Arrow Function
ES6 odds = evens.map(v => v + 1) pairs = evens.map(v => ({ even: v, odd: v + 1 })) nums = evens.map((v, i) => v + i)
ES5 odds = evens.map(function (v) { return v + 1; }); pairs = evens.map(function (v) { return { even: v, odd: v + 1 }; }); nums = evens.map(function (v, i) { return v + i; });
14
Statement Bodies Arrow Function
ES6 nums.forEach(v => { if (v % 5 === 0)
fives.push(v) })
ES5 nums.forEach(function (v) { if (v % 5 === 0)
fives.push(v); });
15
Lexical this Arrow Function
ES6 this.nums.forEach((v) => { if (v % 5 === 0)
this.fives.push(v) })
ES5 // variant 1 var self = this; this.nums.forEach(function (v) {
if (v % 5 === 0) self.fives.push(v);
}); // variant 2 (since ECMAScript 5.1 only) this.nums.forEach(function (v) {
if (v % 5 === 0) this.fives.push(v);
}.bind(this));
17
Default Parameter Values
ES6 function f (x, y = 7, z = 42) { return x + y + z
} f(1) === 50
ES5 function f (x, y, z) { if (y === undefined)
y = 7; if (z === undefined) z = 42; return x + y + z;
}f(1) === 50;
18
Rest Parameters
ES6 function f (x, y, ...a) { return (x + y) * a.length
} f(1, 2, "hello", true, 7) === 9
ES5 function f (x, y) { var a = Array.prototype.slice.call(arguments, 2); return (x + y) * a.length;
}; f(1, 2, "hello", true, 7) === 9;
19
Spread ParametersES6 var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ] // [ 1, 2, "hello", true, 7 ] f(1, 2, ...params) === 9
var str = "foo" var chars = [ … str ] // [ "f", "o", "o" ]
ES5 var params = [ "hello", true, 7 ]; var other = [ 1, 2 ].concat(params); // [ 1, 2, "hello", true, 7 ] f.apply(window, other) === 9;
var str = "foo"; var chars = str.split(""); // [ "f", "o", "o" ]
20
Template Strings
ES6 var customer = {name: "Foo" } var card = { amount: 7, product: "Bar", unitprice: 42 } message = `Hello ${customer.name}, want to buy ${card.amount} ${card.product} for a total of ${card.amount * card.unitprice} bucks?`
ES5 var customer = { name: "Foo" }; var card = { amount: 7, product: "Bar", unitprice: 42 }; message = "Hello " + customer.name + ",\n" + "want to buy " + card.amount + " " + card.product + " for\n" + "a total of " + (card.amount * card.unitprice) + " bucks?";
22
Property Shorthand
ES6 var x = 10, y = 20;obj = { x, y }
ES5 var x = 10, y = 20;obj = { x: x, y: y };
23
Computed Property Names
ES6 obj = { foo: "bar", [ "prop_" + foo() ]: 42
}
ES5 obj = { foo: "bar"
}; obj[ "prop_" + foo() ] = 42;
24
Method PropertiesES6
obj = { foo (a, b) {
… }, bar (x, y) {
… }, *quux (x, y) {
… }
}
ES5
obj = { foo: function (a, b) {
… }, bar: function (x, y) {
… }, // quux: no equivalent in ES5
};
25
Destructuring Assignment
Array Matching Object Matching, Shorthand
Notation Object Matching, Deep Matching Parameter Context Matching
26
Array Matching
ES6 var list = [ 1, 2, 3 ] var [ a, , b ] = list [ b, a ] = [ a, b ]
ES5 var list = [ 1, 2, 3 ]; var a = list[0], b = list[2]; var tmp = a; a = b; b = tmp;
27
ES6 var { op, lhs, rhs } = getASTNode()
ES5 var tmp = getASTNode(); var op = tmp.op; var lhs = tmp.lhs; var rhs = tmp.rhs;
Object Matching, Shorthand Notation
28
ES6 var { op: a, lhs: { op: b }, rhs: c } = getASTNode()
ES5 var tmp = getASTNode(); var a = tmp.op; var b = tmp.lhs.op; var c = tmp.rhs;
Object Matching, Deep Notation
29
Parameter Context Matching
ES6
function f ([ name, val ]) { console.log(name, val) } function g ({ name: n, val: v }) {
console.log(n, v) } function h ({ name, val }) { console.log(name, val) } f([ "bar", 42 ]) g({ name: "foo", val: 7 }) h({ name: "bar", val: 42 })
ES5
function f (arg) { var name = arg[0]; var val = arg[1]; console.log(name, val);
}; function g (arg) {
var n = arg.name; var v = arg.val; console.log(n, v);
}; function h (arg) {
var name = arg.name; var val = arg.val; console.log(name, val);
};f([ "bar", 42 ]); g({ name: "foo", val: 7 }); h({ name: "bar", val: 42 });
31
Symbol Export/ImportES6
// lib/math.js
export function sum (x, y) { return x + y
} export var pi = 3.141593
// someApp.js
import * as math from "lib/math"
console.log("2π = " + math.sum(math.pi, math.pi))
// otherApp.js
import { sum, pi } from "lib/math" console.log("2π = " + sum(pi, pi))
ES5
// lib/math.js
LibMath = {}; LibMath.sum = function (x, y) { return x + y }; LibMath.pi = 3.141593;
// someApp.js
var math = LibMath; console.log("2π = " + math.sum(math.pi, math.pi));
// otherApp.js
var sum = LibMath.sum, pi = LibMath.pi; console.log("2π = " + sum(pi, pi));
33
Class DefinitionES6 class Shape {
constructor (id, x, y) { this.id = id this.move(x, y)
} move (x, y) {
this.x = x this.y = y
} }
ES5 var Shape = function (id, x, y) { this.id = id; this.move(x, y);
}; Shape.prototype.move = function (x, y) {
this.x = x; this.y = y;
};
34
Class InheritanceES6 class Rectangle extends Shape {
constructor (id, x, y, width, height) { super(id, x, y) this.width = width this.height = height
} } class Circle extends Shape {
constructor (id, x, y, radius) { super(id, x, y) this.radius = radius
} }
35
Class Inheritance cont.
ES5 var Rectangle = function (id, x, y, width, height) { Shape.call(this, id, x, y); this.width = width; this.height = height;
}; Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle;
var Circle = function (id, x, y, radius) { Shape.call(this, id, x, y);this.radius = radius;
}; Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle;
36
Base Class AccessES6 class Shape {
… toString () { return `Shape(${this.id})` }
} class Rectangle extends Shape {
constructor (id, x, y, width, height) { super(id, x, y) …
} toString () { return "Rectangle > " + super.toString()
} } class Circle extends Shape {
constructor (id, x, y, radius) { super(id, x, y) …
} toString () { return "Circle > " + super.toString() }
}
37
Base Class Access cont.
ES5 var Shape = function (id, x, y) { …
}; Shape.prototype.toString = function (x, y) {
return "Shape(" + this.id + ")" }; var Rectangle = function (id, x, y, width, height) {
Shape.call(this, id, x, y); …
}; Rectangle.prototype.toString = function () {
return "Rectangle > " + Shape.prototype.toString.call(this); }; var Circle = function (id, x, y, radius) {
Shape.call(this, id, x, y); … }; Circle.prototype.toString = function () {
return "Circle > " + Shape.prototype.toString.call(this); };
38
Static MemberES6 class Rectangle extends Shape {
… static defaultRectangle () {
return new Rectangle("default", 0, 0, 100, 100) }
} class Circle extends Shape {
… static defaultCircle () {
return new Circle("default", 0, 0, 100) }
} var defRectangle = Rectangle.defaultRectangle() var defCircle = Circle.defaultCircle()
39
Static Member cont.
ES5 var Rectangle = function (id, x, y, width, height) { …
}; Rectangle.defaultRectangle = function () {
return new Rectangle("default", 0, 0, 100, 100); }; var Circle = function (id, x, y, width, height) {
… }; Circle.defaultCircle = function () {
return new Circle("default", 0, 0, 100); }; var defRectangle = Rectangle.defaultRectangle(); var defCircle = Circle.defaultCircle();
40
Getter / SetterES6 class Rectangle {
constructor (width, height) { this.width = width this.height = height
} set width (width) { this._width = width } get width () { return this._width } set height (height) { this._height = height } get height () { return this._height } get area () { return this.width * this.height }
} var r = new Rectangle(50, 20) r.area === 1000
41
Getter / Setter cont.
ES5 var Rectangle = function (width, height) { this.width = width; this.height = height;
}; Rectangle.prototype = {
set width (width) { this._width = width; }, get width () { return this._width; }, set height (height) { this._height = height; }, get height () { return this._height; }, get area () { return this.width * this.height; }
}; var r = new Rectangle(50, 20); r.area === 1000;
42
Generators
Generator Function, Iterator Protocol
Generator Function, Direct Use Generator Matching Generator Control-Flow
43
Generator Protocol, Iterator Protocol
ES6 let fibonacci = { *[Symbol.iterator]() {
let pre = 0, cur = 1 for (;;) {
[ pre, cur ] = [ cur, pre + cur ] yield cur
} }
} for (let n of fibonacci) {
if (n > 1000) break
console.log(n)}
44
Generator Protocol, Iterator Protocol
ES5 var fibonacci = { next: ((function () {
var pre = 0, cur = 1; return function () {
tmp = pre; pre = cur; cur += tmp; return cur;
}; })();
}; var n; for (;;) {
n = fibonacci.next(); if (n > 1000)
break; console.log(n);
}
45
Generator Function, Direct Use
ES6 function* range (start, end, step) { while (start < end) {
yield startstart += step
} } for (let i of range(0, 10, 2)) {
console.log(i) // 0, 2, 4, 6, 8 }
ES5 function range (start, end, step) { var list = []; while (start < end) {
list.push(start); start += step;
} return list;
} var r = range(0, 10, 2); for (var i = 0; i < r.length; i++) {
console.log(r[i]); // 0, 2, 4, 6, 8 }
46
Generator MatchingES6 let fibonacci = function* (numbers) {
let pre = 0, cur = 1 while (numbers-- > 0) {
[ pre, cur ] = [ cur, pre + cur ] yield cur
} } for (let n of fibonacci(1000))
console.log(n) let numbers = [ ...fibonacci(1000) ] let [ n1, n2, n3, ...others ] = fibonacci(1000)
ES5 // no equivalent in ES5
48
Set Data-StructureES6 let s = new Set()
s.add("hello").add("goodbye").add("hello") s.size === 2 s.has("hello") === true for (let key of s.values()) // insertion order
console.log(key)
ES5var s = {}; s["hello"] = true; s["goodbye"] = true; s["hello"] = true; Object.keys(s).length === 2; s["hello"] === true; for (var key in s) // arbitrary order
if (s.hasOwnProperty(key)) console.log(s[key]);
49
Map Data-StructureES6 let m = new Map()
m.set("hello", 42) m.set(s, 34) m.get(s) === 34 m.size === 2 for (let [ key, val ] of m.entries())
console.log(key + " = " + val)
ES5var m = {}; m["hello"] = 42; // no equivalent in ES5 // no equivalent in ES5 Object.keys(m).length === 2; for (key in m) {
if (m.hasOwnProperty(key)) { var val = m[key]; console.log(key + " = " + val);
} }
51
Promise UsageES6 function msgAfterTimeout (msg, who, timeout) {
return new Promise((resolve, reject) => { setTimeout(() => resolve(`${msg} Hello ${who}!`),
timeout) })
} msgAfterTimeout("", "Foo", 100).then((msg) =>
return msgAfterTimeout(msg, "Bar", 200) ).then((msg) => {
console.log(`done after 300ms:${msg}`) })
ES5 function msgAfterTimeout (msg, who, timeout, onDone) { setTimeout(function () {
onDone(msg + " Hello " + who + "!"); }, timeout); } msgAfterTimeout("", "Foo", 100, function (msg) {
msgAfterTimeout(msg, "Bar", 200, function (msg) { console.log("done after 300ms:" + msg);
}); });
52
Promise CombinationES6 function fetchAsync (url, timeout, onData, onError) {
… } let fetchPromised = (url, timeout) => {
return new Promise((resolve, reject) => { fetchAsync(url, timeout, resolve, reject)
}) } Promise.all([
fetchPromised("http://backend/foo.txt", 500), fetchPromised("http://backend/bar.txt", 500), fetchPromised("http://backend/baz.txt", 500) ]).then((data) => {
let [ foo, bar, baz ] = data console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => { console.log(`error: ${err}`)
})
53
How to use?
No browser has 100% implementation of ES6.
ES6 Shim (Run time) Transpiler (Compile time)
55
AngularAMD
ServiceA js
ServiceB js
Service js
CtrlA js CtrlB js Ctrl js…
…
APP
RouterA RouterB Router…
Demo
Q & A
• https://github.com/dhaval-patel/angularAMDDemo• https://
github.com/dhaval-patel/angularAMDDemoES6