Sei sulla pagina 1di 24

EcmaScript 6

- Avinash Kundaliya

Technische Universitt Mnchen

Agenda
Terminologies

Language Features
Template string
let
Arrow Function
forof loops
Function Parameters
Promise

Demo

Technische Universitt Mnchen

Compatibility

http://kangax.github.io/compat-table/es6/

Technische Universitt Mnchen

Terminologies
JavaScript // the language
EcmaScript // scripting language standard
ES6 (EcmaScript 6) // 6th version of the scripting language standard
ES.next
ES Harmony
TC39 // Technical committee that maintain and update the standard

Technische Universitt Mnchen

Agenda
Terminologies

Language Features
Template string
let
Arrow Function
forof loops
Function Parameters
Promise

Demo

Technische Universitt Mnchen

Template String
Allows string literals with embedded expressions in them.
Multiline strings
Tags (pass through a function)
1varname="TUMunich",
2msg=`Hello,${name}!`;
3
4console.log(msg);
//"Hello,TUMunich!"

Link to Spec : http://tc39wiki.calculist.org/es6/template-strings/

Technische Universitt Mnchen

Template String (contd..)


1varevent_details=`<divclass="event">
2<divclass="day">
3${currentEvent.DTSTART.getDay()}
4${currentEvent.DTSTART.toLocaleString('enUS',{month:
"short"})}
5${currentEvent.DTSTART.getFullYear()}
6</div>
7<divclass="summary">${currentEvent.SUMMARY}</div>
8<divclass="description">${currentEvent.DESCRIPTION}</div>
9<divclass="location">${currentEvent.LOCATION}</div>
10<divclass="clearfix"></div>
11</div>`;

Technische Universitt Mnchen

Template String (tags)


1letname="world";
2tag`Hello${name}!`;
3
4//tag(["Hello","!"],"world")

Can be used for l10n


Escaping
Possibilities are endless

Technische Universitt Mnchen

let

syntactically similar to var


defines a variable in the current block
No hoisting
Basically, a better var

1{leta=blockscopes,yay!';}
2console.log(a);//ReferenceError:aisnotdefined

constant,a baby sister for let


1consta='Constants';
2a='Youshallnotchange';
//SyntaxError:Assignmenttoconstantvariable
Link to Spec : http://tc39wiki.calculist.org/es6/block-scoping/

Technische Universitt Mnchen

Arrow Function
Shorter syntactical form of the function keyword.
(()=>{}vs.function(){})

Lexical this binding.


Lacks a .prototype
No constructor

Link to Spec : http://tc39wiki.calculist.org/es6/arrow-functions/

Technische Universitt Mnchen

Arrow Function (examples)


1letartists=[
2{name:"Michael",songs:55},
3{name:"Max",songs:44}
4];
5console.log(artists.map(artist=>artist.name));
6//["Michael","max"]
7
8letsongs=artists.map(artist=>artist.songs);
9console.log(songs.reduce((s1,s2)=>s1+s2));
10//99

Link to Spec : http://tc39wiki.calculist.org/es6/arrow-functions/

Technische Universitt Mnchen

Arrow Function (lexical this binding)


1varmakeRequest=(url)=>{
2this.my_url=url;
3returnnewPromise((resolve,reject)=>{
4lethttpRequest=newXMLHttpRequest();
5httpRequest.onreadystatechange=()=>{
6console.log(this.my_url);
7};
8httpRequest.open('GET',url,true);
9httpRequest.send(null);
10});//promiseobject
11};

Technische Universitt Mnchen

Agenda
Terminologies

Language Features
Template string
let
Arrow Function
forof loops
Function Parameters
Promise

Demo

Technische Universitt Mnchen

forof loops
looping of only iterable objects (Array, Sets, and Maps)
only iterates data, not object properties (like forin)
1for(letwordof[One",Two",Three"])
2console.log(word);
//One,Two,Three

Link to Spec : http://tc39wiki.calculist.org/es6/for-of/

Technische Universitt Mnchen

forin issue
1vararr=['some','text'];
2Array.prototype.each=function(){};
3for(variinarr)
4console.log(i);
5//0,1,each
6
7for(variofarr)
8console.log(i)
9//some,text

Technische Universitt Mnchen

Function Parameters
Rest parameters
deal with arbitrary number of parameters

1functiontest(param1,...restParams){
2console.log(param1);
3console.log(restParams);//alwaysanArray
4}
5test(1,2,4,5);
//1
//[2,4,5]

Technische Universitt Mnchen

Function parameters (contd)


Default parameter values ( forget options=options||{};)
1functiontest(i=3){returni;}
2test();//returns3
1functionthrowMissingError(){
2thrownewError('missingparameter');
3}
4functiontestThrow(requiredParam=throwMissingError()){
5returnrequiredParam;
6}
7
8testThrow();
9//Error:missingparameter
10testThrow(123);
11//123
(http://www.2ality.com/2014/04/requiredparameterses6.html)

Technische Universitt Mnchen

Callback Hell
1$.get("www.api.awesome.com/get/rest",function(data){
2varresponse=DoStuffWithData(data);
3$.getJSON("www.api.test.com/get/test",function(data){
4if(data.isAwesome()){
5SetAwesomeData(data):
6}
7}
8});
9

10$.get("www.api.awesome.com/get/rest")
11.then(doStuffWithData)
12.then(function(data){
13if(data.isAwesome()){
14SetAwesomeData(data);
15}
16})

Technische Universitt Mnchen

Promise
Promise for a value to be returned in a future
Can have three mutually exclusive states
fulfilled
rejected
pending
Can be referred as deferred or future
Powerful for asynchronous / concurrent applications

Link to Spec : http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects

Technische Universitt Mnchen

Promise (examples)
1varpromise=newPromise(function(resolve,reject){
2//doathing,possiblyasync,then
3if(/*everythingturnedoutfine*/){
4resolve("Stuffworked!");
5}
6else{
7reject(Error("Itbroke"));
8}
9});
1promise.then(function(result){
2console.log(result);//"Stuffworked!"
3},function(err){
4console.log(err);//Error:"Itbroke"
5});

Technische Universitt Mnchen

How to use it today?


Firefox Nightly

Chrome Canary

Traceur compiler

http:// github.com/google/traceur-compiler
node 0.11.x (with -harmony flag)
Chrome enable experimental flags
Firefox <scripttype="application/javascript;version=1.7

Technische Universitt Mnchen

class
yet to be implemented in major browsers
Maximally-Minimal Class
uses the class keyword
has constructor, getters and setter
can be extend(ed)
super is available in sub classes

module
yet to be implemented in major browsers
Adds a module loading system
Makes the global scope sensible

DEMO
iCAL Reader
https://bitbucket.org/avk/es6-seminar

Questions?

Potrebbero piacerti anche