SlideShare uma empresa Scribd logo
1 de 57
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

Mais conteúdo relacionado

Mais procurados

1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
retronym
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
vidyamittal
 
Difrentiation
DifrentiationDifrentiation
Difrentiation
lecturer
 

Mais procurados (20)

Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
 
Collection v3
Collection v3Collection v3
Collection v3
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonads
 
Eta
EtaEta
Eta
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
Pengolahan Data Panel Logit di Stata: Penilaian Goodness of Fit, Uji Model, d...
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Низкоуровневые оптимизации .NET-приложений
Низкоуровневые оптимизации .NET-приложенийНизкоуровневые оптимизации .NET-приложений
Низкоуровневые оптимизации .NET-приложений
 
Difrentiation
DifrentiationDifrentiation
Difrentiation
 
MATHS SYMBOLS - EXPONENTIALS + LOGARITHMS and THEIR PROPERTIES
MATHS SYMBOLS - EXPONENTIALS + LOGARITHMS and THEIR PROPERTIESMATHS SYMBOLS - EXPONENTIALS + LOGARITHMS and THEIR PROPERTIES
MATHS SYMBOLS - EXPONENTIALS + LOGARITHMS and THEIR PROPERTIES
 
S1 3 derivadas_resueltas
S1 3 derivadas_resueltasS1 3 derivadas_resueltas
S1 3 derivadas_resueltas
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
Living in the ES6 Future, Today
Living in the ES6 Future, TodayLiving in the ES6 Future, Today
Living in the ES6 Future, Today
 

Semelhante a ES6 and AngularAMD

ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
hayato
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
Solution4Future
 

Semelhante a ES6 and AngularAMD (20)

Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
Javascript
JavascriptJavascript
Javascript
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

ES6 and AngularAMD

  • 1. C o n f i d e n t i a l ECMASCRIPT6 ANGULAR AMD July, 2015 Dhaval Patel
  • 2. 2 Agenda  Introduction to ES6  Features of ES6  Usage of ES6  Introduction to AMD  Usage of Require with Angular  Demo  Q&A
  • 3. 3 ECMAScript  What is ES?  History  Current Version  Problems with Current Version
  • 4. 4 ES5 Problems  Global Variable  ‘this’ Problem  Scope Variables / Functions  Callbacks
  • 5. 5 Introduction ES6  The next 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
  • 9. 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. 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. 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. 12 Arrow Functions  Expression Bodies  Statement Bodies  Lexical this
  • 13. 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. 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. 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. 16 Extended Parameter Handling  Default Parameter Values  Rest Parameters  Spread Operator
  • 17. 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. 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. 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. 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. 21 Extended Object Properties  Property Shorthand  Computed Property Names  Method Properties
  • 22. 22 Property Shorthand ES6 var x = 10, y = 20; obj = { x, y } ES5 var x = 10, y = 20; obj = { x: x, y: y };
  • 23. 23 Computed Property Names ES6 obj = { 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  Array Matching  Object Matching, Shorthand Notation  Object Matching, Deep Matching  Parameter Context Matching
  • 26. 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. 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 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. 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. 32 Class  Class Definition  Class Inheritance  Base Class Access  Static Member  Getter/Setter
  • 33. 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. 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. 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. 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. 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. 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. 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. 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. 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. 42 Generators  Generator Function, Iterator Protocol  Generator Function, Direct Use  Generator Matching  Generator Control-Flow
  • 43. 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. 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. 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. 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. 47 Map & Set  Set Data-Structure  Map Data-Structure
  • 48. 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. 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. 50 Promises  Promise Usage  Promise Combination
  • 51. 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. 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. 53 How to use?  No browser has 100% implementation of ES6.  ES6 Shim (Run time)  Transpiler (Compile time)
  • 54. 54 AngularAMD  What is Angular Js?  What is AMD?  How to use AMD with Angular?
  • 55. 55 AngularAMD ServiceA js ServiceB js Service js 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