KEMBAR78
ES6 and AngularAMD | PPTX
C o n f i d e n t i a l
ECMASCRIPT6
ANGULAR AMD
July, 2015
Dhaval Patel
2
Agenda
 Introduction to ES6
 Features of ES6
 Usage of ES6
 Introduction to AMD
 Usage of Require with Angular
 Demo
 Q&A
3
ECMAScript
 What is ES?
 History
 Current Version
 Problems with Current Version
4
ES5 Problems
 Global Variable
 ‘this’ Problem
 Scope Variables / Functions
 Callbacks
5
Introduction ES6
 The next major version of JavaScript
 Modular
 Much readable
 Lesser Code
 More control
6
Features
 Constants
 Scope
 Module
 Class
 Promise
7
Constants
ES6 const PI = 3.141593
PI > 3.0
ES5
Object.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
8
Scoping
 Block-scoped variable
 Block-scoped function
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;
})();
12
Arrow Functions
 Expression Bodies
 Statement Bodies
 Lexical this
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));
16
Extended Parameter Handling
 Default Parameter Values
 Rest Parameters
 Spread Operator
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 Parameters
ES6 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 + " forn" +
"a total of " + (card.amount * card.unitprice) + " bucks?";
21
Extended Object Properties
 Property Shorthand
 Computed Property Names
 Method Properties
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 Properties
ES6
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 });
30
Module
 Symbol Export/Import
31
Symbol Export/Import
ES6
// 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));
32
Class
 Class Definition
 Class Inheritance
 Base Class Access
 Static Member
 Getter/Setter
33
Class Definition
ES6 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 Inheritance
ES6 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 Access
ES6 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 Member
ES6 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 / Setter
ES6 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 start
start += 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 Matching
ES6 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
47
Map & Set
 Set Data-Structure
 Map Data-Structure
48
Set Data-Structure
ES6 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)
ES5
var 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-Structure
ES6 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)
ES5
var 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);
}
}
50
Promises
 Promise Usage
 Promise Combination
51
Promise Usage
ES6 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 Combination
ES6 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)
54
AngularAMD
 What is Angular Js?
 What is AMD?
 How to use AMD with Angular?
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
Thank You

ES6 and AngularAMD

  • 1.
    C o nf i d e n t i a l ECMASCRIPT6 ANGULAR AMD July, 2015 Dhaval Patel
  • 2.
    2 Agenda  Introduction toES6  Features of ES6  Usage of ES6  Introduction to AMD  Usage of Require with Angular  Demo  Q&A
  • 3.
    3 ECMAScript  What isES?  History  Current Version  Problems with Current Version
  • 4.
    4 ES5 Problems  GlobalVariable  ‘this’ Problem  Scope Variables / Functions  Callbacks
  • 5.
    5 Introduction ES6  Thenext major version of JavaScript  Modular  Much readable  Lesser Code  More control
  • 6.
    6 Features  Constants  Scope Module  Class  Promise
  • 7.
    7 Constants ES6 const PI= 3.141593 PI > 3.0 ES5 Object.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
  • 8.
  • 9.
    9 Blocked-scoped variables withouthoisting 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.
    10 Blocked-scoped variables withhoisting 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.
    11 Blocked-scoped Function ES6 { functionfoo () { 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; })();
  • 12.
    12 Arrow Functions  ExpressionBodies  Statement Bodies  Lexical this
  • 13.
    13 Expression Bodies ArrowFunction 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.
    14 Statement Bodies ArrowFunction ES6 nums.forEach(v => { if (v % 5 === 0) fives.push(v) }) ES5 nums.forEach(function (v) { if (v % 5 === 0) fives.push(v); });
  • 15.
    15 Lexical this ArrowFunction 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));
  • 16.
    16 Extended Parameter Handling Default Parameter Values  Rest Parameters  Spread Operator
  • 17.
    17 Default Parameter Values ES6function 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.
    18 Rest Parameters ES6 functionf (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.
    19 Spread Parameters ES6 varparams = [ "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.
    20 Template Strings ES6 varcustomer = {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 + " forn" + "a total of " + (card.amount * card.unitprice) + " bucks?";
  • 21.
    21 Extended Object Properties Property Shorthand  Computed Property Names  Method Properties
  • 22.
    22 Property Shorthand ES6 varx = 10, y = 20; obj = { x, y } ES5 var x = 10, y = 20; obj = { x: x, y: y };
  • 23.
    23 Computed Property Names ES6obj = { foo: "bar", [ "prop_" + foo() ]: 42 } ES5 obj = { foo: "bar" }; obj[ "prop_" + foo() ] = 42;
  • 24.
    24 Method Properties ES6 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.
    25 Destructuring Assignment  ArrayMatching  Object Matching, Shorthand Notation  Object Matching, Deep Matching  Parameter Context Matching
  • 26.
    26 Array Matching ES6 varlist = [ 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.
    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.
    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.
    29 Parameter Context Matching ES6 functionf ([ 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 });
  • 30.
  • 31.
    31 Symbol Export/Import ES6 // lib/math.js exportfunction 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));
  • 32.
    32 Class  Class Definition Class Inheritance  Base Class Access  Static Member  Getter/Setter
  • 33.
    33 Class Definition ES6 classShape { 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.
    34 Class Inheritance ES6 classRectangle 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.
    35 Class Inheritance cont. ES5var 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.
    36 Base Class Access ES6class 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.
    37 Base Class Accesscont. 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.
    38 Static Member ES6 classRectangle 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.
    39 Static Member cont. ES5var 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.
    40 Getter / Setter ES6class 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.
    41 Getter / Settercont. 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.
    42 Generators  Generator Function,Iterator Protocol  Generator Function, Direct Use  Generator Matching  Generator Control-Flow
  • 43.
    43 Generator Protocol, IteratorProtocol 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.
    44 Generator Protocol, IteratorProtocol 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.
    45 Generator Function, DirectUse ES6 function* range (start, end, step) { while (start < end) { yield start start += 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.
    46 Generator Matching ES6 letfibonacci = 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
  • 47.
    47 Map & Set Set Data-Structure  Map Data-Structure
  • 48.
    48 Set Data-Structure ES6 lets = 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) ES5 var 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.
    49 Map Data-Structure ES6 letm = 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) ES5 var 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); } }
  • 50.
  • 51.
    51 Promise Usage ES6 functionmsgAfterTimeout (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.
    52 Promise Combination ES6 functionfetchAsync (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.
    53 How to use? No browser has 100% implementation of ES6.  ES6 Shim (Run time)  Transpiler (Compile time)
  • 54.
    54 AngularAMD  What isAngular Js?  What is AMD?  How to use AMD with Angular?
  • 55.
    55 AngularAMD ServiceA js ServiceB js Servicejs CtrlA js CtrlB js Ctrl js… … APP RouterA RouterB Router …
  • 56.
    Demo Q & A •https://github.com/dhaval-patel/angularAMDDemo • https://github.com/dhaval-patel/angularAMDDemoES6
  • 57.