ecmascript 6

32
<web /F> <web/F> ECMAScript 6 An Overview

Upload: webf

Post on 19-Aug-2015

41 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: ECMAScript 6

<web/F>  <web/F>  

ECMAScript  6 An  Overview  

Page 2: ECMAScript 6

<web/F>  <web/F>  

What  we  need  ? •  Code  organiza0on  •  Readability    •  Syntax  Improvement  for  basic  opera0ons  •  More  Control  •  Be@er  support  for  Unicode  •  Get  rid  of  workarounds  •  Predictability        

Page 3: ECMAScript 6

<web/F>  <web/F>  

Func8on  Parameters  -­‐-­‐  Default  Values //ECMA5 function multiply(a, b ) { b = typeof b == 'number' ? b : 1; return a*b; } //ECMA6 function multiply(a, b = 1) { return a*b; }  

Page 4: ECMAScript 6

<web/F>  <web/F>  

Func8on  Parameters  -­‐-­‐  Computa8on function singularAutoPlural(

singular, plural = singular+"s", rallyingCry = plural + " ATTACK!!!") {

return [singular, plural, rallyingCry ]; }  

Page 5: ECMAScript 6

<web/F>  <web/F>  

Func8on  Parameters  -­‐-­‐  Rest  Params function add(a,...all){

var sum=a; all.forEach(function(value){ sum+=value; }) return sum;

}  

Page 6: ECMAScript 6

<web/F>  <web/F>  

Spread  Operator var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; //ECMA 5 way Array.prototype.push.apply(arr1, arr2); //ECMA 6 way arr1.push(...arr2);//arr1.push(3,4,5) function add(a,b){ return a+b; } add(...arr2);//7

Page 7: ECMAScript 6

<web/F>  <web/F>  

Object  Literal  -­‐  Short  hand var first=”A”,

last=”Z”; //ECMA5 way var obj = { first: first,

last: last, foo:function(){} };

//ECMA6 var obj = { first,

last, foo(){} };

Page 8: ECMAScript 6

<web/F>  <web/F>  

Object  Literal  -­‐  Computed,  GeIer,  SeIer //ECMA5 var obj={}; obj['a'+0]='value'; //ECMA6 var obj={

['a'+0]:'value', get name(){ return 'hello';}

}

Page 9: ECMAScript 6

<web/F>  <web/F>  

for-­‐of   //iterate values let arr = ['foo', 'bar', 'baz']; for (let element of arr) {

console.log(element);//for,bar,baz }

Page 10: ECMAScript 6

<web/F>  <web/F>  

Octal  and  Binary  Literals 0o10 == 8 0O10 == 8 0b10 == 2 0B10 == 2 Number('0b01')==1

Page 11: ECMAScript 6

<web/F>  <web/F>  

String  Templates var name = 'Jane'; var str = `Hi ${name}! 3

plus 4 is ${3+4}`; console.log(str);//Hi Jane 3 plus 4 is 7 //tagged template for customization

Page 12: ECMAScript 6

<web/F>  <web/F>  

Destructuring var [a,b]=["value1","value2"]; var [a,,b]=[0,1,2]; var [a,b,...c]=[0,1,2,3,4]; var {first,last}={first:"A",last:"Z"}; var {first:f,last:target}={first:"A",last:"Z"}; Console.log(f);//A

Page 13: ECMAScript 6

<web/F>  <web/F>  

Block  Func8ons

function foo(){

'use strict';

function fun(){return 'outer';}

if(true){

function fun(){return 'inner';}

fun();//inner

}

fun();//outer

}

Page 14: ECMAScript 6

<web/F>  <web/F>  

Block  Variables

let a=20;

for(let i=0;i<10;i++){

let value=i;

setTimeout(function(){

console.log(value);

},1);

}

Page 15: ECMAScript 6

<web/F>  <web/F>  

Constants

const bar = 123;

bar = 45; // error in strict mode

{ const bar = 456; }

bar === 123;

Page 16: ECMAScript 6

<web/F>  <web/F>  

Arrow  Func8ons

//ECMA5

var arr = [1, 2, 3];

var squares = arr.map(function(x){ return x*x; });

//ECMA6

let arr = [1, 2, 3];

let squares = arr.map(x => x * x);

Page 17: ECMAScript 6

<web/F>  <web/F>  

Arrow  Func8ons  -­‐  this

// `this` is picked up from surroundings (lexical)

// Therefore: no more `that = this` or bind()

function UiComponent {

let button = document.getElementById('myButton');

button.addEventListener('click', () => {

console.log('CLICK');

this.handleClick(); // lexical `this`

});

}

Page 18: ECMAScript 6

<web/F>  <web/F>  

Arrow  Func8ons  -­‐  Usage

no argument

() => Math.random();

one argument

x => x*x;

multiple arguments

(x,y) => x*y;

rest parameters

(x,y,..all) => x*y*all.length;

returning object

(x) =>({value:x})

Multiple statements

(x,y) => { doSomething(x,y); return x*y;}

Page 19: ECMAScript 6

<web/F>  <web/F>  

Class

Extension

Super reference

constructor

static methods, properties

Page 20: ECMAScript 6

<web/F>  <web/F>  

Class

class Person {

constructor(name) { this.name = name; },

describe() { return 'Person called ' + this.name; }

}

class Employee extends Person {

static employer(){ return “Globant”; },

constructor(name, title) {

super(name);

this.title = title;

},

describe() {return super.describe() + '(' + this.title + ')'; }

}

Page 21: ECMAScript 6

<web/F>  <web/F>  

Generators

function* idMaker(){

var index = 0;

while(index < 3)

yield index++;

}

for(var k of idMaker()){ console.log(k) }//0,1,2

var gen = idMaker();

console.log(gen.next().value); // 0

console.log(gen.next().value); // 1

console.log(gen.next().value); // 2

console.log(gen.next().value); // undefined

Page 22: ECMAScript 6

<web/F>  <web/F>  

Generators  -­‐  Delega8on

function* g1() {

yield 2;

}

function* g2() {

yield 1;

yield* g1();

}

var iterator = g2();

console.log(iterator.next()); // { value: 1, done: false }

console.log(iterator.next()); // { value: 2, done: false }

console.log(iterator.next()); // { value: undefined, done: true }

Page 23: ECMAScript 6

<web/F>  <web/F>  

Proxies  -­‐  Set

let validator = {

set: function(obj, prop, value) {

if (prop === 'age') {

if (!Number.isInteger(value)){throw new TypeError('The age is not an integer');}

if (value > 200) {throw new RangeError('The age seems invalid');}

}

obj[prop] = value;

}

};

let person = new Proxy({}, validator);

person.age = 100;

console.log(person.age); // 100

person.age = 'young'; // Throws an exception

person.age = 300; // Throws an exception

Page 24: ECMAScript 6

<web/F>  <web/F>  

Proxies  -­‐  Get

var handler = {

get: function(target, name){

return name in target?

target[name] : 37;

}

};

var p = new Proxy({}, handler);

p.a = 1;

p.b = undefined;

console.log(p.a, p.b); // 1, undefined

console.log('c' in p, p.c); // false, 37

Page 25: ECMAScript 6

<web/F>  <web/F>  

Modules  

//------ lib.js ------

export const sqrt = Math.sqrt;

export function square(x) {

return x * x;

}

//------ main.js ------

import { square, diag } from 'lib';

console.log(square(11)); // 121

//System.import

Page 26: ECMAScript 6

<web/F>  <web/F>  

Symbols  

//new kind of primitive value

//each symbol is unique

Symbol()==Symbol();//false

Symbol.for("sym")//Symbol(sym)

Symbol("sym")==Symbol.for("sym");//false

Page 27: ECMAScript 6

<web/F>  <web/F>  

Symbols  

var myIterable = {};

myIterable[Symbol.iterator] = function* () {

yield 1;

yield 2;

yield 3;

};

[...myIterable] // [1, 2, 3]

Page 28: ECMAScript 6

<web/F>  <web/F>  

Map  and  Set  

var m = new Map(),s={};

m.set("hello", 42);

m.set(s, 34);

m.get(s) == 34;

//object, size , order in enumeration

var s = new Set();

s.add("hello").add("goodbye").add("hello");

s.size === 2;

s.has("hello") === true;

Page 29: ECMAScript 6

<web/F>  <web/F>  

WeakMap  and  WeakSet  

var wm = new WeakMap(),s={};

wm.set(s, { extra: 42 });

wm.size === undefined

WeakSet: add,delete,has only

//Only Objects

//garbage collection

//no size property

//no enumeration

Page 30: ECMAScript 6

<web/F>  <web/F>  

More..

Unicode support

Subclassing a builtins

Promises

Reflect

Tail Call Optimization,

New API’s - Math,Number,String,Array,Object

Page 31: ECMAScript 6

<web/F>  <web/F>  

Current  Support

h@ps://kangax.github.io/compat-­‐table/es6/  Browsers  •  Firefox-­‐39:66%  ,  FF41:69%  • MicrosoS  Edge  :  66%  • Chrome:56%    Compiler  Babel  :  71%  Traceur:59%      

Page 32: ECMAScript 6

<web/F>  <web/F>  

What  we  need  ? •  Code  organiza0on  –  Classes,modules  

•  Readability  –  destructuring,  arrow  func0ons,  classes,  extend,  super  •  Syntax  Improvement  for  basic  opera0ons  –  rest,  spread,    destructuring  •  More  Control  –  Proxies,  super,  symbol  

•  Be@er  support  for  Unicode  -­‐-­‐    regex  flags,  string  length  •  Get  rid  of  workarounds  –  Default  Parameter  Value,  let  ,  const  

•  Predictability  –  Scope  Func0ons,  let,  const  •  Performance  –  Generators,  Tail  Call  Op0miza0on