es ecmascript2015 2015...class admin extends user{constructor(name, country,...
TRANSCRIPT
ES2015ECMAScript2015
@korzh_sergii 2016
ECMAScriptECMAScript — это встраиваемый расширяемый не имеющий средств ввода-вывода язык программирования, используемый в качестве основы для построения других скриптовых языков. Стандартизирован международной организацией ECMA в спецификации ECMA-262.
Реализации ECMAScript: JavaScript, ActionScript, JScript, QtScript.
let a = 5;
console.log(a); // 5
{
let b = 5;
}
console.log(b); // b is not defined
ES2015
let, const
const A = “123";
A = “321"; // Assignment to constant variable.
const A = “567"; // Identifier 'A' has already been declared
let str = "JavaScript";let arr = [...str];
console.log(arr); // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
ES2015
Spread Operator
let [first, second, ...spread] = ["destructuring", "assignment", "spread", "operator"];
console.log(first); // destructuring
console.log(second); // assignment
console.log(spread); // ["spread", "operator"]
console.log(...spread); // spread operator
ES2015
Destructuring assignment && Spread operator
[second, first] = [first, second];console.log(first); // assignment
console.log(second); // destructuring
ES2015
Destructuring assignment && Spread operator
function def(x, y){
var x = x || 2;
var y = y || 3;
console.log( x+y) ;
}
def(4); // 7
ES2015
Default properties
function def(x=2, y=3){
console.log(x+y);
}
def(4); // 7
let fun = str => console.log(str);fun("Helllo!"); // Helllo!
let fun2 = (x, y, z=4) => {
let sum = x+y+z;
console.log(sum);
}
fun2(1, 2); // 7
ES2015
Arrow function
let obj = { arr: [1, 2, 3, 4], res: [], square: function(){ this.arr.forEach( (v) => { console.log(this); // Object this.res.push( v*v ); } ); console.log(this.res); }}obj.square(); // [1, 4, 9, 16]
ES2015Arrow function
ES5 function
square: function(){
this.arr.forEach( function(v) {
console.log(this); // Window this.res.push( v*v );
} );
console.log(this.res);
}
let str = `2 + 2 = ${2+2}`; console.log(str); // 2 + 2 = 4
let name = "John";
console.log(`Hello ${name}`); // Hello John
ES2015
Template string
let arr = [1, 2, 4];console.log(`${arr}`); // 1, 2, 4
let [first="Template", second] = [ , "string"];
console.log(`${first}, ${second}`); // Template string
ES2015
Template string
let object = { name: 'John',
email: '[email protected]',
role: 'admin‘
};
let {name, email, role} = object;
console.log(name); // John
console.log(email); // [email protected]
console.log(role); // admin
ES2015
Object properties
let x = 1;let y = 2;
let obj = {x, y};
console.log( obj.x+ " " +obj.y ); // 1 2
let name = “firstName”;
let user = { [name]: “John” };
console.log( user.firstName ); // John
ES2015
Object properties
let x = {x: 2};
let y = {y: 8};
let obj = Object.assign({}, x, y);
console.log(obj); // Object {x: 2, y: 8}
ES2015
Object.assign()
class User{
constructor(name, country){
this.name = name;
this.country = country;
}
get info(){ return `My name is ${this.name}, I’m from ${this.country}`; }
greeting(){ console.log("Hello!"); }
}
let man = new User('John', 'UK');
man.greeting(); // Hello!
console.log(man.info); // My name is John, I’m from UK
ES2015Class
class Admin extends User{ constructor(name, country, role='admin'){ super(name, country); this.role = role; } get info(){ return `${super.info}. And I’m admin`; } set newCountry(country){ this.country = country; }}
let admin = new Admin('Jack', 'UK', 'admin');admin.greeting(); // Hello!console.log(admin.info); // My name is Jack, I’m from UK. And I’m admin
admin.newCountry = 'DE';console.log(admin.info); // My name is Jack, I’m from DE. And I’m admin
ES2015Class
class Human{
constructor(){ /*….*/ }
static think(){
console.log(“Human is thinking...");
}
sleep(){
console.log(“Human is sleeping...");
}
}
Human.think(); // Human is thinking...
Human.sleep(); // TypeError: Human.sleep is not a function
ES2015Class
let Human = class {
constructor(){ }
}
let man = new Human();
ES2015Class
let Human = class Man{
constructor(){ }
}
let man = new Man(); // Man is not defined
let range = { from: 1, to: 5 }
range[Symbol.iterator] = function() { let current = this.from; let last = this.to;
return { next() { if (current <= last) { return { done: false, value: current++ }; }
ES2015Iterator
else { return { done: true };}}}};
for (let num of range) { console.log(num); // 1, 2, 3, 4, 5}
function* generator(){ yield "Learn"; yield "ES"; return "2015";}
let a = generator();let b = a.next();console.log(b); // Object {value: "Learn", done: false}
b = a.next();console.log(b); // Object {value: "ES", done: false}
b = a.next();console.log(b); // Object {value: "2015", done: true}
ES2015Generator
function loadData(url){ return new Promise(resolve, reject){ let request = new XMLHttpRequest(); request.open("GET", url); request.onload = function(){ if( request.status === 200 ){ resolve(request.response); } else{ reject( Error("Error code:" +request.statusText) ); } } request.send(null);}}
ES2015Promise
loadData('url.com').then(
function(response){
document.body.innerHTML(response.value);
},
function(Error){
console.warn(Error);
});
ES2015Promise
export {name as user, greeting, User};
let name = "John";
function greeting(){ console.log("Hello");}
class User{ constructor(name){ this.name = name;}}
ES2015export
import {name, greeting, User} from "./info";
console.log(name); // John
import * as userInfo from '/info';
console.log(userInfo.user); // John
ES2015import
export default class User{
constructor(name){
this.name = name;
}
}
import User from "./user“;
ES2015export, import
let m = new Map();
m.set('name', 'John');
m.set('age', 25);
console.log(m); // Map {"name" => "John", "age" => 25}
console.log(m.get('name')); // John
ES2015Map
let s = new Set("hello");
s.add("h").add("e").add("l").add("l").add("o");
console.log(s); // Set {"h", "e", "l", "o"}
ES2015Set
let dictionary = { 'Hello': 'Привет', 'Bye': 'Пока'};
dictionary = new Proxy(dictionary, { get( target, phrase ) { if ( phrase in target ) { return target[phrase]; } else { console.log(`No phrase: ${phrase}`); return phrase; }}})
ES2015Proxy
console.log( dictionary['Hello'] ); //
Привет
console.log( dictionary['Welcome'] );
// No phrase: Welcome
// Welcome
get(target, property, receiver) - срабатывает при чтении свойства;
set(target, property, value, receiver) - срабатывает при записи;
has(target, property) - срабатывает аналогично get, но только при проверке наличия
свойства
deleteProperty(target, property) - отрабатывает на событие delete
enumerate(target) - ловит переборы for...in, for...of
apply(target, thisArgument, argumentsList) - ловит событие вызова функции
construct(target, argumentsList) - ловит событие new
ES2015Proxy
let symbol = Symbol('symbol');
let symbol2 = Symbol.for('symbol');
console.log(symbol == symbol2); // false
console.log(Symbol.keyFor(symbol)); // undefined
console.log(Symbol.keyFor(symbol2)); // symbol
let obj = {[Symbol.for('name')]: "John"};
console.log(obj[Symbol.for('name')]); // John
ES2015Symbol
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler
https://kangax.github.io/compat-table/es6/
https://learn.javascript.ru/es-modern
http://denysdovhan.com/slides-promises/#/?_k=zhjzgp
https://www.youtube.com/watch?v=4YfsAz-sNAo&index=1&list=PLqHlAwsJRxAOpWPtj2T6HhSzX-lKmKV2q
ES2015Links
ES2015ECMAScript2015
@korzh_sergii 2016