ECMA 6 - O futuro já começou

Saiba tudo sobre a mais nova versão da Ecmascript

Yan Magalhães

Web Developer na

Ciência da Computação (In progress)

Agenda

  • A Ecmascript
  • Ecmascript International
  • Funcionalidades da Ecma2015
  • Dicas
  • It's show time
  • Explore o mundo

https://slides.com/yanmagale/es6-o-futuro-ja-comecou

ECMA 6 - O futuro já começou

Saiba tudo sobre a mais nova versão da Ecmascript

AVISO: 

Essa palestra terá muito código.

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

Futuro? Não

Já 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 = "Dev In University"
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

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, conseguimos fazer também?

SIM \o/\o/

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 

Indo Além

Promises

Uma biblioteca 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, "DevInUniversity", 200))
.then((msg) =>
    msgAfterTimeout(msg, "UNA", 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

E já posso utilizar tudo isso nos navegadores?

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

https://babeljs.io/

Explore o mundo

Indo Além

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

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

Obrigado Galera \o/

https://slides.com/yanmagale/es6-o-futuro-ja-comecou

Ecma 6:O futuro já começou!

By Yan Magalhães

Ecma 6:O futuro já começou!

Palestra apresentada no evento DevInUniversity, na Facudade UNA, 04/06/2016

  • 1,470