ES6 для чайников

Обзор базовых возможностей ES6

👶 ES6 для чайников

История

История развития JavaScript
Хронология развития JavaScript

Поддержка браузерами

Источник: https://kangax.github.io/compat-table/es6/
Поддержка браузерами JavaScript

Транспалинг

Babel

Babel.JS – это транспайлер, переписывающий код на ES6 в код на предыдущем стандарте ES5

Он состоит из двух частей:

  1. Транспайлер, который переписывает код
  2. Полифилл, который добавляет методы Array.from, String.prototype.repeat и другие

Главные возможности ES6

Важно!

Весь код ниже должен выполнятся в строгом режиме.

Это значит нужно использовать директиву "use strict";

Babel поставит поставит директиву сам

Подробнее: Директива use strict

Стреляем по ногам вместе с var

Block scope variables

      
        var x = "outer";
        function test(inner) {
          if (inner) {
            var x = "inner"; // scope whole function
            return x;
          }
          return x; // gets redefined on line 4
        }
        
        test(false); // undefined
        test(true); // inner
      
    

Царские let и const

Итог

Block scope variables

      
        (function(){ 
          var private = 1;
        })();

        {
          let private = 2;
        }

        console.log(private); // Uncaught ReferenceError
      
    

Шаблонные строки (Template Literals)

      
        const first = "John";
        const last = "Doe";

        console.log("Your name is " + first + " " + last + ".");
        console.log(`Your name is ${first} ${last}.`);
      
    

Многострочные шаблоны ES5

      
        const template =
        "<div class=\"select\">\n" + 
        "  <label for=\"select\">" + label + "<label>"
        "  <select name=\"select\" id=\"select\">\n" +
        "    <option value=\"value\">text</option>\n" +
        "  </select>\n" +
        "</div>";

      const style = 
        "height: "+ height + "px;" +
        "width: "+ width + "px;" +
        "padding: 15px 6px 0;";
      
    

Многострочные шаблоны ES6

      
        const template =
          `<div class="select">
            <label for="select">${label}<label>
            <select name="select" id="select">
              <option value="value">text</option>
            </select>
          </div>`;

        const style = `
          height: ${height}px;
          width: ${width}px;
          padding: 15px 6px 0;
        `;
      
    

Деструктуризация (Destructuring Assignment)

Деструктуризация – это особый синтаксис присваивания, при котором можно присвоить массив или объект сразу нескольким переменным, разбив его на части.

      
        const [firstName, lastName] = ["John", "Doe"];
      
        const { firstName, lastName } = { 
          firstName: "John",
          lastName: "Doe"
        };
      
    

Примеры использования деструктуризации

      
        function getFullName({ firstName, lastName }) {
          return `${firstName} ${lastName}`;
        }

        users.map(
          function({ firstName, lastName }) {
            return getFullName({ firstName, lastName });
          }
        )
      
    

Глубокое сопоставление

      
        const settings = {
          display: { color: "red" },
          keyboard: { layout: "querty" }
        };

        const {
          display: { color: displayColor },
          keyboard: { layout: keyboardLayout }
        } = settings;
      
    

Стрелочные функции

      
        button.addEventListener('click', (event) => {
          this.sendData(); // ?
        });

        // implicit returns
        const ids = [291, 288, 984];
        const messages = ids.map(value => `ID is ${value}`);
        
        const getFullName = ({ firstName, lastName }) =>
          `${firstName} ${lastName}`;
      
    

Стрелочные функции

      
        const zeroArgs = () => {/* ... */}
        const zeroWithUnderscore = _ => {/* ... */}
        const oneArg = arg1 => {/* ... */}
        const oneArgWithParenthesis = (arg1) => {/* ... */}
        const manyArgs = (arg1, arg2) => {/* ... */}
        const oneArgWithDestriction = ({ one, two }) => {/* ... */}
        const returnData = (a, b) => a + b;
        const notReturn = () => { someFinction(); }
      
    

ООП

Классы

        
          var Animal = (function () {
            function MyConstructor(name) {
              this.name = name;
            }
            MyConstructor.prototype.speak = function speak() {
              console.log(this.name + ' makes a noise.');
            };
            return MyConstructor;
          })();

          var animal = new Animal('animal');
          animal.speak(); // animal makes a noise.
        
      

Классы

      
        class Animal {
          constructor(name) {
            this.name = name;
          }
          speak() {
            console.log(this.name + ' makes a noise.');
          }
        }

        const animal = new Animal('animal');
        animal.speak(); // animal makes a noise.
      
    

Геттеры и сеттеры

      
        class User {
          constructor(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
          }
          get fullName() {
            return `${this.firstName} ${this.lastName}`;
          }
          set fullName(newValue) {
            [this.firstName, this.lastName] = newValue.split(' ');
          }
        }
      
    

Наследование

      
        class Lion extends Animal {
          speak() {
            super.speak();
            console.log(this.name + ' roars ');
          }
        }

        const lion = new Lion('Simba');
        lion.speak(); // Simba makes a noise.
        // Simba roars.
      
    

Советы

Callback hell

      
        function printAfterTimeout(string, timeout, done){
          setTimeout(function(){ done(string); }, timeout);
        }

        printAfterTimeout('Hello ', 2e3, function(result){
          console.log(result);
          // nested callback
          printAfterTimeout(result + 'Reader', 2e3, function(result){
            console.log(result);
          });
        });
      
    

Нативные промисы

      
        function printAfterTimeout(string, timeout){
          return new Promise((resolve, reject) => {
            setTimeout(function(){ resolve(string); }, timeout);
          });
        }
        
        printAfterTimeout('Hello ', 2e3).then((result) => {
          console.log(result);
          return printAfterTimeout(result + 'Reader', 2e3);
        }).then((result) => {
          console.log(result);
        });
      
    

For...of

ES6 for...of позволяет использовать итераторы

      
        // массив — пример итерируемого объекта
        let arr = [1, 2, 3]; 

        for (let value of arr) {
          alert(value); // 1, затем 2, затем 3
        }
      
    

Параметры по умолчанию

      
        // ES5
        function point(_x, _y, _isFlag) {
          var x = _x || 0;
          var y = _y || -1; 
          var isFlag = _isFlag || true;
          console.log(x,y, isFlag);
        }

        // ES6
        function point(x = 0, y = -1, isFlag = true) {
          console.log(x,y, isFlag);
        }
      
    

Spread operator

      
        // Математические функции
        Math.max.apply(Math, [2,100,1,6,43]) // 100
        Math.max(...[2,100,1,6,43]) // 100

        // Обьединение
        console.log([...array1, ...array2, ...array3]);
        console.log({...object1, ...object2, ...object3});

        // Клонирование
        var arr = [1,2,3];
        var arr2 = [...arr];
      
    

Spread operator

      
        // Вызов функции
        function doStuff (x, y, z) { }
        var args = [0, 1, 2];

        // ES5
        doStuff.apply(null, args);

        // ES6
        doStuff(...args);
      
    

Rest-параметры

      
        function printf(format) {
          var params = [].slice.call(arguments, 1);
          console.log('params: ', params);
          console.log('format: ', format);
        }

        function printf(format, ...params) {
          console.log('params: ', params);
          console.log('format: ', format);
        }
      
    

Расширенные литералы объектов

      
        const name = "John";
        const user = {
          name,
          hello(name) {
            return `Hello ${name}`;
          },
          [`user_${name}`.toUpperCase()]: "",
        };
      
    

Модули

Модули

Модулем считается файл с кодом.

В этом файле ключевым словом export помечаются переменные и функции, которые могут быть использованы снаружи.

Другие модули могут подключать их через вызов import.

Системы организации модулей

export

      
        export let one = 1;
        export { one, two };
        export { one as once, two as twice };
        export class User { /* ... */ };
        export function sayHi() { /* ... */ }
      
    

У функции и у класса при таком экспорте должно быть имя

import

      
        import { one, two } from "./nums";
        import { one as item1, two as item2 } from "./nums";
        import * as numbers from "./nums";

        // nums.js
        export let one = 1; 
        export let two = 2;
      
    

export default

Для ситуации, когда один модуль экспортирует одно значение, предусмотрено особое ключевое сочетание export default.

      
        export default class User {
          constructor(name) {
            this.name = name;
          }
        };

        // login.js
        import User from './user';
        const user = new User("Jhon");
      
    

String

String.includes()

Проверяет, включает ли одна строка в себя другую, возвращает

      
        var string = "food";
        var substring = "foo";

        // ES5
        console.log(string.indexOf(substring) > -1); // true

        // ES6
        console.log(string.includes(substring)); // true
      
    

String.repeat()

Проверяет, включает ли одна строка в себя другую, возвращает

      
        'meow'.repeat(3); // "meowmeowmeow"
      
    

Object

Object.assign()

Функция Object.assign получает список объектов и копирует в первый target свойства из остальных.

      
        const original = [0, 1, 2, 3];
        const clone = Object.assign([], original, { 2: 42 }); 
        // [0, 1, 42, 3]

        const user = { name: "John" };
        const visitor = { isAdmin: false, visits: true };
        const admin = { isAdmin: true };

        const newUser = Object.assign(user, visitor, admin);
      
    

Object.keys()

      
        var arr = ["a", "b", "c"];
        console.log(Object.keys(arr)); // ["0", "1", "2"]

        var anObj = { 100: "a", 2: "b", three: "c" };
        console.log(Object.keys(anObj)); // ["2", "100", "three"]
      
    

Array

Array.map()

Используется для трансформации массива

        
          const numbers = [1, 4, 9];
          const roots = numbers.map(Math.sqrt); // [1, 2, 3]
          const doubles = numbers.map(function(num) {
            return num * 2;
          });
          // doubles = [2, 8, 18]
        
      

Array.from()

Создаёт новый экземпляр Array из массивоподобного или итерируемого объекта

        
          const itemElements = document.querySelectorAll('.items');
          const items = Array.from(itemElements);

          items.forEach(function(element) {
              console.log(element.nodeType)
          });
        
      

Array.filter()

Используется для фильтрации массива через функцию

        
          function isBigEnough(value) {
            return value >= 10;
          }
          
          const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
          // [12, 130, 44]
        
      

Array.reduce()

Используется для последовательной обработки каждого элемента массива с сохранением промежуточного результата

      
        const arr = [0, 1, 2, 3, 4];
        const total = arr.reduce(
          (previousValue, currentValue, index, array) => {
            return previousValue + currentValue;
          }); 
        // total = 10
      
    

Другие полезные методы Array

Что осталось за бортом?

Бонус

Fetch API

Полифилл whatwg-fetch

      
        const newUser = fetch("/users", {
          method: "POST",
          headers,
          body: JSON.stringify({ name, login })
        })
        .then(checkStatus)
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log("Request failed", error));
      
    

Ссылки

git.io/es6fd