Сегодня я собираюсь показать вам три наиболее часто используемых функции ES6 (EcmaScript 2015), которые лично я использую каждый день на работе.
TL;DR:
const – let: константы и переменные с блочной областью действия.
Функции со стрелками:Функции с более коротким синтаксисом.
Деструктуризация: создание переменных непосредственно из других объектов.
Во-первых, я начну с функции, которую использую чаще всего: const и let.
константа и пусть
- const позволяет объявить константу со значением только для чтения.
const name = "Joe"; // If we try to reassign it, we'll get an error name = "Mike"; // Uncaught TypeError: Assignment to constant variable. // Additionally we can't declare it without assigning a value const name; // SyntaxError: Missing initializer in const declaration
Примечание.При использовании объектов мы можем изменять значения свойств, поскольку мы не переназначаем объект:
const myDog = { name: "Homero", breed: "Labrador" }; // If we change a property it won't throw an error myDog.name = "Pedro"; myDog.name = "Poodle"; // This will myDog = { name: "Pedro", breed: "Poodle" }; // Uncaught TypeError: Assignment to constant variable.
- С другой стороны, у нас есть let:
Это новое ключевое слово объявляет переменную, которую можно инициализировать без значения.
let name = "Joe"; // This is also possible let name; name = "Joe"
Эти два новых ключевых слова имеют блочную область действия. Что это обозначает? По сути, область действия переменных, созданных с помощью let и const, будет существовать только внутри области условий if и switch или for и пока. Вообще говоря, они будут жить внутри { } (фигурные скобки), где они были объявлены.
if (someCondition) { const msg = "It's true"; } console.log(msg); // Uncaught ReferenceError: msg is not defined
То же самое происходит с let:
for (let i = 0; i < 3; i++) { console.log(i); } console.log(i); // 0 // 1 // 2 // Uncaught ReferenceError: i is not defined // If we would've used var instead, "i" would be 3 at this point
Стрелочные функции
Это новый тип функций с очень интересными функциями, такими как более короткий синтаксис и ключевое слово this, прикрепленное к его родительскому элементу, а не к локальной области видимости.
Я просто расскажу о синтаксисе, чтобы сделать этот пост максимально простым. Ознакомиться с другими преимуществами можно здесь.
Давайте посмотрим на них в действии:
// Normal function function sum(a, b) { return a + b; } // Arrow function const sum = (a, b) => { return a + b; } // Anonymous arrow function setTimeout(() => { console.log('Anon function!'); }, 100); // There is also a shorter syntax for returning a value // Just wrap it in parenthesis const sum = (a, b) => ( a + b ); // We can make it even shorter if it's just a line const sum = (a, b) => a + b; // If the function has only one parameter we can omit the parenthesis const sumTwo = num => num + 2;
Разрушение
Как следует из названия, это позволит нам деструктурировать объект или массив в одну или несколько переменных. Давайте посмотрим, как это работает:
Разрушение объектов:
// We have a simple object const car = { weels: 4, doors: 5 } // We use {curly brackets} to destructure an object const { weels } = car; // This is going to create a constant named "weels" with the value of the property "weels" from the object "car" console.log(weels); // 4 // Pretty cool huh? We can even define multiple variables within the same statement const { weels, doors } = car; console.log(weels); // 4 console.log(doors); // 5
Разрушение массивов:
// Suppose we have the following array const colors = ["blue", "red", "green"]; // We use [square brackets] to destructure an array and give the name that we want to the variable/s. The assignments are going to be made in the order the elements are stored in the array. const [blue, red] = colors; console.log(primaryColor); // "blue" console.log(secondaryColor); // "red" // We can ignore values we're not interested in const [firstColor, , secondColor] = colors; console.log(firstColor); // "blue" console.log(secondColor); // "green" // Some pretty cools things can be done, like swapping variable values let a = 1; let b = 2; [a, b] = [b, a]; console.log(a); // 2 console.log(b); // 1 // Passing an array returned from a function const returnArray = () => { return [1, 2]; } const [firstValue, secondValue] = returnArray(); console.log(firstValue); // 1 console.log(secondValue); // 2
И это пока все! Более подробную информацию вы можете найти здесь:
Есть еще много возможностей ES6, с которыми вы можете ознакомиться здесь.