ECMAScript 2015

Wesley Amaro
Pedro Araujo

Introdução ao

// TC-39 - FLUXO DE NOVAS FEATURES

// TC-39 - FLUXO DE NOVAS FEATURES

O comitê Ecma TC39 é responsável por evolução da linguagem de programação EcmaScript e criar sua especificaçao.

// TC-39 - FLUXO DE NOVAS FEATURES

// TC-39 - FLUXO DE NOVAS FEATURES

FLUXO DE NOVAS FEATURES

Strawman

Proposal

Draft

Candidate

Finished

Permite  a entrada de novas propostas

// TC-39 - FLUXO DE NOVAS FEATURES

FLUXO DE NOVAS FEATURES

Strawman

Proposal

Draft

Candidate

Finished

Descreve os critérios e levanta possíveis problemas

// TC-39 - FLUXO DE NOVAS FEATURES

FLUXO DE NOVAS FEATURES

Strawman

Proposal

Draft

Candidate

Finished

Descreve a sintaxe e a semântica com especificação formal da linguagem

// TC-39 - FLUXO DE NOVAS FEATURES

FLUXO DE NOVAS FEATURES

Strawman

Proposal

Draft

Candidate

Finished

Indica que futuros refinamentos requer feedback dos implementadores e usuários

// TC-39 - FLUXO DE NOVAS FEATURES

FLUXO DE NOVAS FEATURES

Strawman

Proposal

Draft

Candidate

Finished

Indica que a feature está pronta para ser adicionada no EcmaScript

// LET and CONST 

var golDoBrasil = 1;
var golDaAlemanha = 7; 

{

    let golDoBrasil = 7;
    var golDaAlemanha = 1;
    
    golDoBrasil; // 7
    golDaAlemanha; // 1


}

golDoBrasil; // 1
golDaAlemanha; // 1
const mundialPalmeiras = 0;
mundialPalmeiras = 1;

// TypeError: Assignment to constant variable.


const palmeiras = {
    numMundial: 1;
}

palmeiras.numMundial = 0;
palmeiras.numMundial; // 0
Let: Declara uma variável local no escopo do bloco atual, opcionalmente iniciando-a com um valor.

Const: Cria uma referência read-only do valor.

// FOR OF vs FOR IN

for...in itera sobre todas as propriedades enumeráveis do objeto.

// 0

// 1

// 2

// size

let bigTeams = ['Santos', 'Flamengo', 'Atlético Mineiro'];

bigTeams.size = 3;

for ( let team in bigTeams ) {
    console.log(team);
}

// FOR OF vs FOR IN

for...of itera em objetos iteráveis, tipo arrays.

// Santos

// Flamengo

// Atlético Mineiro

let bigTeams = ['Santos', 'Flamengo', 'Atlético Mineiro'];

bigTeams.size = 3;

for ( let team of bigTeams ) {
    console.log(team);
}

// NEW IIFES

(function() {
    var cleber = "BIRRRLLL";
})();

console.log(cleber); // Reference error;
{
    let cleber = "SUBI EM ARVORE É O CAR@$@#...";
}

console.log(cleber); // Reference error;
Tendo em mente que var tem como escopo a função pela qual foi definida, com o let são em blocos, logo temos uma nova maneira de fazer "iifes"

// ARROW FUNCTIONS

Sintaxe mais curta e sempre anônimo.
let sum = function(a, b) {
    return a + b;
}

// Arrow Function
let sum = (a, b) => a + b;

// ARROW FUNCTIONS

let arr = ['Santos', 'São Paulo', 'Corinthians'];

let teams = arr.map( function(team) {
    return team + ' tem mundial de clubes';
});
// Arrow Function
let arr = ['Santos', 'São Paulo', 'Corinthians'];

let teams = arr.map( team => {
    return team + ' tem mundial de clubes';
});

// ARROW FUNCTIONS - This léxico

function Palmeiras() {
  this.mundiais = 0;

  setInterval(function titulos() {
    this.mundiais++;
    console.log(this.mundiais);
  }, 1000);
}

var p = new Palmeiras();
Antes das arrow functions, toda nova função definia seu próprio valor de this

ES3/5

// undefined

// ARROW FUNCTIONS - This léxico

function Santos() {
    var _this = this;  
    
    this.mundiais = 2;

    setInterval(function titulos() {
        _this.mundiais++;
        console.log(_this.mundiais);
    }, 1000);
}

var s = new Santos();

// 3

// 4

// 5

...

// ARROW FUNCTIONS - This léxico

function Santos() {  
    this.mundiais = 2;

    setInterval(() => {
        this.mundiais++;
        console.log(this.mundiais);
    }, 1000);
}

var s = new Santos();
Arrow functions capturam o valor de this do contexto vinculado,  deste modo o código a seguir funciona conforme esperado.

ES6

// LITERAL TEMPLATES

const HTML = `<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CHORA BOTA...</title>
</head>
<body>
	
</body>
</html>`;
var golCorinthians = 6;
var golSantos = 1;

console.log(`Eterno ${golCorinthians + 1} x ${golSantos}`); 

// Eterno 7 x 1
Template strings são literais string que permitem expressões embutidas. Você pode usar string multi-linhas e interpolação de string com elas.

// DEFAULT PARAMS

Permite que você defina parâmetros default nas definições de funções.

 

ES3/5

var entrevistaRogerioCeni = function(msg){
    msg = typeof msg !== 'undefined' ?  msg : 'O São Paulo deu uma bambiada';
    return msg;
}
ES6
let entrevistaRogerioCeni = (msg = 'O São Paulo deu uma bambiada') => msg;

entrevistaRogerioCeni(); // O São Paulo deu uma bambiada
entrevistaRogerioCeni('bambiou'); // bambiou

// SPREAD OPERATOR REST PARAMS

function myFunction(...args) {
    console.log(args.length);
}

myFunction(1, 2); // 2

myFunction(1, 2, 3); // 3
var membros = ["joelho", "e pé"];

var musica = ["cabeca", "ombro", ...membros, ...membros];

console.log(musica); // ["cabeca","ombro","joelho","e pé","joelho","e pé"]
O spread operator permite ser expandida em locais onde múltiplos argumentos ou múltiplos elementos são esperados.
A sintaxe rest params permite representar um número infinito de argumentos em um array.

// CLASSES

var Santos = function(estaduais, libertadores) {
   this.estaduais = estaduais;
   this.libertadores = libertadores;
};
 
Santos.prototype.calcularQtde = function() {
  return this.estaduais + this.libertadores;
};

Santos.prototype.getEstaduais = function() {
  return this.estaduais;
};

Santos.prototype.getLibertadores = function() {
  return this.libertadores;
}; 

var s = new Santos(22, 3);

// CLASSES

class Santos {
    constructor(estaduais = 22, libertadores = 3) {
        this.estaduais = estaduais;
        this.libertadores = libertadores;
    }

    calcularQtde() {
        return this.estaduais + this.libertadores;
    }

    getEstaduais() {
        return this.estaduais;
    }

    getLibertadores() {
        return this.libertadores;
    }
}

let s = new Santos();

// CLASSES

class Carro {
    constructor() {
        console.log("Indo comprar um novo carro");
    }
}

class Mercedez extends Carro {
    constructor() {
        super();
        console.log("Comprei uma mercedez");
    }
}

let m = new Mercedez();

// Indo comprar um novo carro
// Comprei uma mercedez

console.log('Obrigado! :D');

ECMAScript 2015 (ES6)

By Wesley Amaro

ECMAScript 2015 (ES6)

  • 624