Все для создания и продвижения сайтов

Верстка, программирование, SEO

Заметки по JS (ECMAScript 6)

1. Переменые let

if(true){
    var version1 = 'ES5';
}

if(true){
    let version2 = 'ES6';
}
console.log(version1); // ES5
console.log(version2); // Error

Пример с кнопками:

// Создадим 5 <button></button> в html
let buttons = document.querySelectorAll('button');
// При button.onclick всегда будет "5"
for(var i = 0; i < buttons.length; i++){
    var button = buttons[i];
    button.innerText = i;
    button.onclick = function (e) {
        console.log(i); 
    }
}
// При button.onclick будет 1,2,3,4,5
for(let i = 0; i < buttons.length; i++){
    var button = buttons[i];
    button.innerText = i;
    button.onclick = function (e) {
        console.log(i);
    }
}

2. Константы const

const PI = 3.14;
const PI = 3.15; // Ошибка

const MATH = {
    PI: 3.14
};

MATH.PI = 3.15; 

console.log(MATH); // 3.15

3. Оператор разворота

let staticLanguages = ['C','C++','Java'];

let dynamicLanguages = ['PHP', 'JS', 'Ruby'];

let Languages = [...staticLanguages,'C#', ...dynamicLanguages, 'Python'];

// ["C", "C++", "Java", "C#", "PHP", "JS", "Ruby", "Python"]
console.log(Languages);

function add(x,y,z) {
    console.log(x+y+z);
}

let number = [1,2,3];

add(...number);// 6

4. Шаблонные строки

function f(name) {
    console.log("Hello " + name); // Hello bill
    console.log(`Hello ${name}`); // Hello bill
}
f('bill');

// Вывод с новой строки
function f1(to,from,subject,message) {
    console.log(`
        to: ${to}
        from: ${from}
        subject: ${subject}
        message: ${message}
    `);
}
f1('test@test.ru','test2@mail.ru','Hello','How are you?');
// to: test@test.ru
// from: test2@mail.ru
// subject: Hello
// message: How are you?

function f2(x,y) {
    console.log(`${x} + ${y} = ${x + y}`)
}

function f3(x,y) {
    console.log(`${x} + ${y} = ${parseInt(x) + parseInt(y)}`)
}

f2(5,7); // 5 + 7 = 12
f2('5','7'); // 5 + 7 = 57
f3('5','7'); // 5 + 7 = 12

function upperName(literals, value) {
    return literals[0]+value.toUpperCase();
}

let name = 'Bill';
console.log(upperName`Hello ${name}`); // Hello BILL

5. Параметры функции

function greet1(greeting,name) {
    console.log(`${greeting} ${name}`)
}

greet1("Hi","Bill"); // Hi Bill
greet1("Hi"); // Hi undefined

function greet2(greeting = 'Hello', name = 'Friend') {
    console.log(`${greeting} ${name}`)
}

greet2("Hi","Bill"); // Hi Bill
greet2("Hi"); // Hi Friend

function sum(...values) {
    let sum = 0;
    /*
    values.forEach(function (value) {
        sum += value;
    });
    console.log(sum);
    */
    // Тоже самое
    console.log(values.reduce(function (prevValue,currentValue) {
       return prevValue + currentValue
    }));
}

sum(4,3,2); // 9    

6. Циклы (for...of)

let browsers = ['Chrome', 'Firefox', 'Opera', 'Edge'];

// 1 2 3 4
for(let browser in browsers){
    console.log(browser);
}

// Chrome Firefox Opera Edge
for(let index in browsers){
    console.log(browsers[index]);
}

// Chrome Firefox Opera Edge
for(let browser of browsers){
    console.log(browser);
}

7. Объекты

let firstName = 'Bill';
let lastName = 'Geits';
let email = 'bill@mc.com';

let person1 = {
    firstName: firstName,
    lastName: lastName,
    email: email,
};

let person2 = {
    firstName,
    lastName,
    email,
    sayHello() {
        console.log(`Hi my name is ${this.firstName} ${this.lastName}`)
    }
};

console.log(person1); // {firstName: "Bill", lastName: "Geits", email: "bill@mc.com"}
console.log(person2); // {firstName: "Bill", lastName: "Geits", email: "bill@mc.com", sayHello: ƒ}
person2.sayHello(); // Hi my name is Bill Geits
console.log(person2.firstName); // Bill
console.log(person2['lastName']); // Geits

let property = 'firstName';
console.log(person2[property]); // person2['firstName'] // Bill

// Динамические свойства

let person3 = {
  [property]: 'Ivan',
};

console.log(person3.firstName); // Ivan

// Разновидности создания динамичных свойств
function createCar(property, value) {
    return{
        [property]: value,
        ['_'+ property]: value,
        [property.toUpperCase()]: value,
        ['get'+property](){
            return this[property];
        }
    }
}

console.log(createCar('vin','123')); // {vin: "123", _vin: "123", VIN: "123", getvin: ƒ}

let person4 = {
    firstName,
    lastName,
    email,
    sayHello() {
        console.log(`Hi my name is ${this.firstName} ${this.lastName}`)
    },
    get fullname(){
        return this.firstName + ' ' + this.lastName;
    },
    set _firstName(name){
        this.firstName = name;
    }
};

person4._firstName = 'Ivan';
console.log(person4.fullname); // Ivan Geits
console.log(person4); // {firstName: "Ivan", lastName: "Geits", email: "bill@mc.com", sayHello: ƒ}

8. Классы

class Task {

    /*
    В ES6 нельзя:
    let title;
    static let count = 0;
    */

    constructor(title = Task.getDefaultTitle()){
        this.title = title;
        this.done = false;
        // Изменения стат. свойств
        Task.count += 1;
    }

    complete(){
        this.done = true;
    }

    // Статический метод
    static getDefaultTitle(){
        return 'Обычная задача';
    }
}

// Статические свойства//
Task.count = 0;

let task1 = new Task('Задача');
let task2 = new Task('Задача 2');
let task3 = new Task();

console.log(task1); // Task {title: "Задача", done: false}
console.log(task2); // Task {title: "Задача 2", done: false}
task1.complete();
console.log(task1); // Task {title: "Задача", done: true}
console.log(Task.count); // 3
console.log(task3); // Task {title: "Обычная задача", done: false}

// GET и SET

class TaskSecond {

    constructor(title = TaskSecond.getDefaultTitle()){
        this.title = title;
        this._done = false;
    }

    get done(){
        return this._done === true ? 'Выполнена' : 'Не выполнена';
    }

    set done(value){
        if(value !== undefined && typeof value === 'boolean'){
            this._done = value;
        }else{
            console.error('Ошибка, укажите значение true или false');
        }
    }
    complete(){
        this._done = true;
    }
}

let task4 = new TaskSecond('Убраться');
console.log(task4.done); // Не выполнена
task4.done = 123; // Ошибка, укажите значение true или false
task4.done = true;
console.log(task4.done); // Выполнена

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

class Task{
    constructor(title){
        this._title = title;
        this._done = false;
        Task.count += 1;
    }

    complete(){
        this._done = true;
        console.log(`Задача ${this.title} выполнена `)
    }

    set title(value){
        this._title = value;
    }

    get title(){
        return this._title;
    }

    static getDefaultTitle(){
        return 'Задача';
    }
}

class SubTask extends Task{
    constructor(title,priority = 0){
        super(title);
        this.priority = priority;
    }

    complete(){
        //this._done = true;
        super.complete();
        console.log(`Подзадача ${this.title} выполнена `)
    }
}

Task.count = 0;

let task = new Task();
task.title = 'Learn JS';
let subtask = new SubTask();
subtask.title = 'Learn ES6';

console.log(task); // Task {_title: "Learn JS", _done: false}
console.log(subtask); // SubTask {_title: "Learn ES6", _done: false, priority: 0}

task.complete(); // Задача Learn JS выполнена
subtask.complete(); // Подзадача Learn ES6 выполнена

console.log(SubTask.getDefaultTitle()); // Задача
console.log(Task.count); // 2

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


let add = (x,y) => x + y;
let sqr = x => x*x;
let sometext = () => 'Text';
let log = () => console.log('test');
let multy = (x,y) => {
    let result = x * y;
    return result
};

let getPersone = () => ({name : 'Jack'});

console.log(add(3,2));
console.log(sqr(3));
console.log(sometext());
log();
console.log(multy(3,5));
console.log(getPersone());

(function () {
    console.log('Самовызывающеюся функция: IIFE');
})();
(() => console.log('Самовызывающеюся функция: IIFE'))();


// Массивы

let numbers = [1,2,3,4,5,6,7,8,9,10];

let sum = 0;

numbers.forEach(function (num) {
   sum += num;
});
numbers.forEach(num => {sum += num});

console.log(sum);

// Map - применение функции на каждый элемент массива
let squared = numbers.map(function (n) {
   return n*n;
});

let squared = numbers.map(n => n*n);


console.log(squared);

// Объекты

let Men = {
    name: 'Jhon',
    greet: function(){
        setTimeout(function () {
            console.log(`Hello my name is ${this.name}`); // Hello my name is
            console.log(this); // Window...
        }, 1000);
    }
};

let Men = {
    name: 'Jhon',
    greet: function(){
        setTimeout(() => {
            console.log(`Hello my name is ${this.name}`); // Hello my name is Jhon
            console.log(this); // {name: "Jhon", greet: ƒ}
        }, 1000);
    }
};


Men.greet();

11. Деструктурирующее присваивание. Массивы


// Обычный способ
let languages = ['JavaScript','PHP','SQL','Ruby'];
let js = languages[0];
let php = languages[1];
let sql = languages[2];
let ruby = languages[3];

console.log(js,php,sql,ruby); // JavaScript PHP SQL Ruby

// Попроще
let languages = ['JavaScript','PHP','SQL','Ruby'];
let js,php,sql,ruby;
[js,php,sql,ruby] = languages;
console.log(js,php,sql,ruby); // JavaScript PHP SQL Ruby

// Ещё проще
let languages = ['JavaScript','PHP','SQL','Ruby'];
let [js,php,sql,ruby] = languages;
console.log(js,php,sql,ruby); // JavaScript PHP SQL Ruby

// Ваще изи
let [js,php,sql,ruby] = ['JavaScript','PHP','SQL','Ruby'];
console.log(js,php,sql,ruby); // JavaScript PHP SQL Ruby


let scores = [3,4,5];
let [low, mid, hight , heigher] = scores;
console.log(low,mid,hight,heigher); // 3 4 5 undefined

// Пропуск значений
let scores = [3,4,5];
let [low, , hight] = scores;
console.log(low,hight); // 3 5

// Остаточные данные
let scores = [3,4,5];
let [low, ...all] = scores;
console.log(low,all); // 3 [4, 5]

// Со значение по умолчанию
let scores = [3,4];
let [low, mid, hight = 5] = scores;
console.log(low,mid,hight); // 3 4 5

// Вставка массивов
let scores = [3,4,[5,6]];
let [low, mid, hight] = scores;
console.log(low,mid,hight); // 3 4 [5, 6]

// Вытаскивание массивов
let scores = [3,4,[5,6]];
let [low, mid, [hight,heigher]] = scores;
console.log(low,mid,hight, heigher); // 3 4 5 6

// Функции
function computeScore([low,mid]) {
    console.log(low,mid);
}

computeScore([3,4]); // 3,4

function getScores() {
    return [3,4,5];
}

let [low,mid,hight] = getScores();

console.log(low,mid,hight); // 3 4 5

// Простой switch значений переменных
let yes = 'yes';
let no = 'no';
[yes, no] = [no, yes];

console.log(yes, no); // no yes

12. Деструктурирующее присваивание. Объекты


// Классический вариант
let person = {
    firstName: 'Jhon',
    lastName: 'Black'
};
let firstName = person.firstName;
let lastName = person.lastName;
console.log(firstName,lastName); // Jhon Black

// Тоже самое
// Имена переменных должны совпадать со свойствами объекта
let {firstName, lastName} = person;
console.log(firstName,lastName); // Jhon Black

// Переименовывание переменных
let {firstName: first, lastName: last} = person;
console.log(first,last); // Jhon Black

// Сразу с объектом
let {firstName: first, lastName: last} =  {firstName: 'Jhon', lastName: 'Black'};
console.log(first,last); // Jhon Black

// Значение по умолчанию
let {firstName: first, lastName: last, age = 25} =  {firstName: 'Jhon', lastName: 'Black'};
console.log(first,last, age); // Jhon Black 25*/

// Динамическое создание
let {['first'+'Name']: first, lastName: last, age = 25} =  {firstName: 'Jhon', lastName: 'Black'};
console.log(first,last, age); // Jhon Black 25

// Вложенные объекты
let user = {
    firstName: 'Jhon',
    lastName: 'Black',
    social: {
        facebook: "jblack",
        twitter: "jhoblack",
        phones: {
            phone1: '11-22-33',
            phone2: '22-33-44'
        }
    }
};
let {firstName: first, lastName: last, social: {facebook: fb,twitter: tw, phones: {phone1: ph1, phone2: ph2}},age = 25} = user;
console.log(first,last,fb,tw,ph1,ph2,age); // Jhon Black jblack jhoblack 11-22-33 22-33-44 25

function post(url,{data,cache}){
    console.log(data,cache);
}
let result = post('api/users',  { data: user, cache: false  }); // {firstName: "Jhon", lastName: "Black", social: {…}} false

function post(url,{data: {firstName, lastName},cache}){
    console.log(firstName,lastName,cache);
}
let result = post('api/users',  { data: user, cache: false  }); // Jhon Black false

// Также можно провернуть такое с функцией, которая возвращает литерал объекта
function getInfoUser() {
    return {
        firstName: 'Jhon',
        lastName: 'Black',
        social: {
            facebook: "jblack",
            twitter: "jhoblack",
        }
    }
}
let {firstName, lastName, social: {facebook, twitter: tw}} = getInfoUser();
console.log(firstName,lastName, facebook, tw); // Jhon Black jblack jhoblack

13. Обещания (promise)


    
Выделите опечатку и нажмите Ctrl + Enter, чтобы отправить сообщение об ошибке.