ES2017+

Vít Jouda,
Dev Center Hradec Králové,
Česká Pojišťovna

opakování

Co je to kontext? Jak s ním můžeme pracovat?

Co je to closure? Jak vznikne?

Jakým způsobem předává JS parametry při volání funkce?

Jaké má JS základní datové typy?

nové modifikátory

let - deklaruje proměnnou s blokovým scope

const - definuje konstantu pouze pro čtení

const constant = 10;
//error
constant = 15;

function testLet(){
    if(true){
        let blockScoped = 30;
        console.log(blockScoped);
    }
    //error
    console.log(blockScoped);
}
testLet();

Defaultní parametry

function multiply(a, b = 1) {
    return a * b;
}

multiply(2);
multiply(2, 4);
// default param will be used
multiply(2, undefined);

function multiply(a, b = 1, c = b * 2) {
    return a * b * c;
}

function increment(state = {
    value: 10}) {
    return Object.assign({}, {value: state.value + 1});
}

String templates

var name = 'Mr. Mock';

console.log(`My name is ${name}`);

var errorTemplate = function(value){ return `Input must have at least ${value} characters` };

console.log(errorTamplate(5));
console.log(errorTamplate(10));

Spread, rest operátor

function add(a, b, c){
    return a + b + c; 
}

var numbers = [0, 1, 2];
//spread operator
console.log(add(...numbers));

var combinedNumbers = [...numbers, 3, 4];
console.log(combinedNumbers);

//rest operator
//contains only unnamed params and is Array unlike arguments
function add(a, ...additionalParams){
    return a + additionalParams.reduce(function(acc, next){
        return acc + next;
    });
}

console.log(add(1, 2, 3));

destructuring

//deconstruct object
var car = {
    brand: 'tesla',
    speed: 240
}

var {speed, brand} = car;
console.log(speed);

//deconstruct function parameter
var items = [
    {
        color: 'red',
        weight: 10
    },{
        color: 'green',
        weight: 7
    }
];

function printColors(items){
    return items.forEach(function({color}){
        console.log(color);
    })
}

printColors(items);

Arrow funkce

let numbers = [0, 1, 2];

numbers.filter((number) => {
    return number % 2 === 0;
});

numbers.filter((number) => number % 2 === 0);

let car = {
    move: () => console.log('I am moving')
}

let curriedAdd = (a) => (b) => a + b;
let addTo5 = curriedAdd(5);
console.log(addTo5(10));

var clock = {
    message: 'Hello',
    sayMessageAfter: function(interval) {
        setTimeout(function(){
            console.log(this.message);
        }, interval);
    }
};

clock.sayMessageAfter(1000);

var clock = {
    message: 'Hello',
    sayMessageAfter: function(interval) {
        setTimeout(() => console.log(this.message), interval);
    }
};

clock.sayMessageAfter(1000);

zjednodušený zápis funkce

lexikálně bindovaný kontext ('this')

nemají implicitní pole argumentů, bind...

třídy

pouze syntactic sugar nad existující prototypální dědičností

es2017 (babel stage-0)

Promise

sync async
single value
multi-value

ES2015 promise

var promise = new Promise((resolve, reject) => {
    resolve(1);
});

promise
    .then((value) => {
        console.log(value);
        return value + 5;
    })
    .then(value => {
        console.log(value);
    });

var errPromise = new Promise((resolve, reject) => {
    reject('Error');
});

errPromise 
    .then((value) => console.log('You should not see this message'))
    .catch((err) => console.log(err));


callback hell

//example using fake API
function send(URL, data, onDone = function(responseData){}){};

send(calculateContract, formData, function(calculatedData ){
    send(saveToDB, calculatedData function(savedData){
            send(print, savedData, function(){
                console.log('Contract printed');
            });   
        });
});

//same example using ES2015 Promise
send(calculateContract, formData)
    .then(function(calculatedData ){
        return send(saveToDB, calculatedData );
    })
    .then(function(savedData){
        return send(print, savedData);
    })
    .then(function(){
        console.log('Contract printed');
    })
    .catch(function(err){
        //handle error
        console.log(err);
    });

//...and with arrow functions
send(calculateContract, formData)
    .then((calculatedData) => send(saveToDB, calculatedData))
    .then((savedData) => send(print, savedData))
    .then(() => console.log('Contract printed'))
    .catch((err) => console.log(err));

cvičení #4

Přepište cvičení #3 s využitím syntaxe ES2015.

ES FIM 2017, ES2017+

By Vít Jouda

ES FIM 2017, ES2017+

ECMAscript FIM presentation 2017, ES2017+

  • 131