ES2015

Você já deveria estar utilizando!

Yan Magalhães

  • Full stack web developer na 4YouSee
  • GDGBH Organizer
  • FEMUG-MG Co-organizer
  • Amante da Web
  • Open Source
  • F1 Fan

Olá!

AVISO: 

Essa palestra terá muito código.

1.

Contexto

Ecmascript?

São os padrões, definições e funcionalidades que os browsers possibilitam para as nossas aplicações web.

EcmaScript International

Entidade responsável por votar e definir quais os padrões e novas funcionalidades

TC39

Harmony = ES6 = ES2015

Devemos (e podemos) utilizar HOJE!

E o que temos de novo?

  • Block scoped
  • Arrow Functions
  • Template Strings
  • Default Params
  • Classes

E o que temos de novo?

  • Modules
  • Promises
  • Map, Set
  • Rest Params
  • E muito, muito mais.

Blocked Scope

Adição das palavras reservadas let e const, para trabalhar melhor com o escopo de variáveis.

const PI = 3.141593
let event = "BH Tec Talks"
console.log(PI > 3.0);

PI = 2; //Uncaught TypeError: Assignment to constant variable.


function f() {
  {
    let x;
    {
      // okay, block scoped name
      const x = "sneaky";
      // error, const
      x = "foo";
    }
    // error, already declared in block
    let x = "inner";
  }
}

Arrow Function

Uma nova sintaxe para declaração de função.

let result = (a, b) => b*a;

console.log(result(10,2)); //20


const foo = () => 'bar'

const baz = (x) => {
  return x + 1
}

const squareSum = (...args) => {
  const squared = args.map(x => Math.pow(x, 2))
  return squared.reduce((prev, curr) => prev + curr)
}

this.items.map(x => this.doSomethingWith(x))

Template Strings

let name = 'Yan';

console.log(`Olá ${name} tudo bem?`);

Default Params

let callMyName = (name="Yan",gretting="Hi ")
=> console.log(gretting,name);

callMyName(); // Hi Yan

Classes

Uma forma mais fácil, amigável e OO Like de se criar classes e métodos.

class Cliente {

  constructor(nome, email) {
    this.nome = nome;
    this.email = email;
  }

  hello() {
    return `Olá ${this.nome} tudo bem?`
  }

  send() {
    return `Enviando email para ${this.email}...`
  }

}


let pessoa = new Cliente('Yan', 'email@email.com');
console.log(pessoa.hello());//Ola Yan tudo bem?
console.log(pessoa.send());//Enviando email para email@email.com

E herança ??

class Character{

    constructor(x,y){
    	this.x = x;
    	this.y = y;
    	this.health_ = 100;
    }

    damage(){
       this.health_ -= 10;
    }

    getHealth() {
      return this.health_;
    }
    toString() {
       return "x: " + this.x + " y: " + this.y 
       + " health: " + this.health_;
    }
}
class Player extends Character{
   constructor(x,y,name){
      super(x,y);
      this.name = name;
   }

   move(dx, dy) {
    this.x += dx;
    this.y += dy;
   }

   toString(){
      return "name: " + this.name 
      + " " + super.toString();
   }
}
//Work

var x = 10
var y = 20

var name = 'Yan';
var character = new Character(x, y);
character.damage();
console.log(character.toString()); // x: 10 y: 20 health: 90

var player = new Player(x, y, name);
player.damage();
player.move(7, 8);
console.log(player.toString()); // name: Yan x: 17 y: 28 health: 90



Modules

Escrever os componentes do seu projeto, reaproveitamento de código e estruturas modulares.

/* solution-math file */

export const PI = 3.141592;

var _sqrt = function(s, x, last){
  return x != last 
  ? _sqrt(s, (x + s / x) / 2.0, x) : x;
};
export function sqrt(s){
  return _sqrt(s, s/2.0, 0.0);
};
export function square(x) {
  return x * x;
};
/* module.js file */

/**
* Utilizing the solution-math
**/

var arg1 = 2;
var arg2 = 3;

import {PI, sqrt, square} from './solution-math'; 
//Load all code of solution-math

console.log(PI);

console.log(sqrt(+arg1)); //Float Number

console.log(square(+arg2)); //Float Number 

Outras Opções

Promises

Uma feature para executar rotinas de forma assíncrona.  É uma representação de um valor que pode ser disponibilizado no futuro.

 

São utilizadas em muitas bibliotecas Javascript.

readFilePromisified('config.json')
.then(function (text) { // (A)
    const obj = JSON.parse(text);
    console.log(JSON.stringify(obj, null, 4));
})
.catch(function (error) { // (B)
    // File read error or JSON SyntaxError
    console.error('An error occurred', error);
});
function msgAfterTimeout (msg, who, timeout) {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve(`${msg} Hello ${who}!`), timeout)
    })
}

msgAfterTimeout("Gretting - ", "Yan", 100)
.then((msg) =>
    msgAfterTimeout(msg, "BH TEC", 200))
.then((msg) =>
    msgAfterTimeout(msg, "Talks", 400))
.then((msg) => {
    console.log(`done after 600ms:${msg}`)
})

Um outro exemplo

Map and Set

// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;


// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;

Rest Params

function f(x, ...y) {
  // y is an Array
  return x * y.length;
}

console.log(f(3, "hello", true) == 6); //true

Destructuring

const arr = ['one!', 'two!', 'three!', 'four!']
const [one, two, ...rest] = arr

const obj = {a: 'x', b: 'y', c: 'z'}
const {a, b, c} = obj

Array Spread

const foo = ['a', 'b', 'c']
const bar = ['d', 'e', 'f']

console.log(...foo)
console.log([...foo, ...bar])

E o suporte dos navegadores?

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

> 90% já suportado

https://babeljs.io/

ES2015 - Indo Além

  • Enhanced Object Literals
  • Iterators + For..Of
  • Tail Calls
  • Generators
  • Unicode
  • Module Loaders
  • Proxies
  • Symbols
  • Binary and Octal Literals
  • Math libraries, Array conversion helpers, String helpers

E tem mais features da linguagem?

2.

ES2016, ES2017 e ES2018

Static Class Properties

class Foo {
  static bar = 'hello'
}

console.log(Foo.bar)

Class Instance Properties

class Cat {
  name = 'Tom'
  state = {
    running: true
  }

  constructor() {
    console.log(this.name, this.state.running)
  }
}

new Cat()

Spread Object

const defaultStyle = {
  color: 'black',
  fontSize: 12,
  fontWeight: 'normal'
}

const style = {
  ...defaultStyle,
  fontWeight: 'bold',
  backgroundColor: 'white'
}

// Note that fontWeight is 'bold', as the second
// assignment overrode the initial assignment.
console.log(style)

Async Functions

const fetchData = async () => {
  return fetch('https://randomuser.me/api/')
}

const printData = async () => {
  try {
    const data = await fetchData()
    const json = await data.json()
    console.log(json)
  } catch(e) {
    console.error("Problem", e)
  }
}

printData()

Dicas

  • https://github.com/lukehoban/es6features
  • https://github.com/yosuke-furukawa/tower-of-babel
  • https://leanpub.com/understandinges6
  • http://exploringjs.com/es6/
  • https://babeljs.io
  • https://github.com/YanMagale/ecma6-studies

/yanmagale

/yaanmagale

/yaanmagalhaes

http://yanmagalhaes.com.br/

Obrigado Galera \o/

https://slides.com/yanmagale/bhtec-es2015

Ecma 2015: você já deveria estar utilizando!

By Yan Magalhães

Ecma 2015: você já deveria estar utilizando!

Palestra apresentada no BH-Tec Talks 2017, 30/08/2017, falando sobre ES2015 e algumas features da ES2016, ES2017 e ES2018

  • 1,314