Обзор базовых возможностей ES6
Babel.JS – это транспайлер, переписывающий код на ES6 в код на предыдущем стандарте ES5
Он состоит из двух частей:
Array.from
,
String.prototype.repeat
и другиеВесь код ниже должен выполнятся в строгом режиме.
Это значит нужно использовать директиву
"use strict";
Babel поставит поставит директиву сам
Подробнее: Директива use strict
var
undefined
for
,
while
и
if
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
let
и
const
– блок
{...}
var
, используйте
let
и
const
.let
вместо
const
(function(){
var private = 1;
})();
{
let private = 2;
}
console.log(private); // Uncaught ReferenceError
const first = "John";
const last = "Doe";
console.log("Your name is " + first + " " + last + ".");
console.log(`Your name is ${first} ${last}.`);
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;";
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;
`;
Деструктуризация – это особый синтаксис присваивания, при котором можно присвоить массив или объект сразу нескольким переменным, разбив его на части.
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.
class
и не изменяйте prototype напрямую. Код будет лаконичнее и его будет легче понять.extends
.
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);
}
// Математические функции
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];
// Вызов функции
function doStuff (x, y, z) { }
var args = [0, 1, 2];
// ES5
doStuff.apply(null, args);
// ES6
doStuff(...args);
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 let one = 1;
export { one, two };
export { one as once, two as twice };
export class User { /* ... */ };
export function sayHi() { /* ... */ }
У функции и у класса при таком экспорте должно быть имя
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 class User {
constructor(name) {
this.name = name;
}
};
// login.js
import User from './user';
const user = new User("Jhon");
Проверяет, включает ли одна строка в себя другую, возвращает
var string = "food";
var substring = "foo";
// ES5
console.log(string.indexOf(substring) > -1); // true
// ES6
console.log(string.includes(substring)); // true
Проверяет, включает ли одна строка в себя другую, возвращает
'meow'.repeat(3); // "meowmeowmeow"
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.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.prototype.find
Array.prototype.values
Array.prototype.entries
Array.prototype.fill
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));