Upgrade to Pro — share decks privately, control downloads, hide ads and more …

es2015

Korzh Sergii
November 23, 2016

 es2015

About new JS features in specification es2015

Korzh Sergii

November 23, 2016
Tweet

More Decks by Korzh Sergii

Other Decks in Programming

Transcript

  1. ECMAScript ECMAScript — это встраиваемый расширяемый не имеющий средств ввода-

    вывода язык программирования, используемый в качестве основы для построения других скриптовых языков. Стандартизирован международной организацией ECMA в спецификации ECMA-262. Реализации ECMAScript: JavaScript, ActionScript, JScript, QtScript.
  2. 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
  3. let str = "JavaScript"; let arr = [...str]; console.log(arr); //

    ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"] ES2015 Spread Operator
  4. 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
  5. [second, first] = [first, second]; console.log(first); // assignment console.log(second); //

    destructuring ES2015 Destructuring assignment && Spread operator
  6. 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
  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
  8. 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] ES2015 Arrow function ES5 function square: function(){ this.arr.forEach( function(v) { console.log(this); // Window this.res.push( v*v ); } ); console.log(this.res); }
  9. let str = `2 + 2 = ${2+2}`; console.log(str); //

    2 + 2 = 4 let name = "John"; console.log(`Hello ${name}`); // Hello John ES2015 Template string
  10. 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
  11. 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
  12. 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
  13. 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()
  14. 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 ES2015 Class
  15. 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 ES2015 Class
  16. 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 ES2015 Class
  17. let Human = class { constructor(){ } } let man

    = new Human(); ES2015 Class let Human = class Man{ constructor(){ } } let man = new Man(); // Man is not defined
  18. 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++ }; } ES2015 Iterator else { return { done: true }; }}}}; for (let num of range) { console.log(num); // 1, 2, 3, 4, 5 }
  19. 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} ES2015 Generator
  20. 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); }} ES2015 Promise
  21. export {name as user, greeting, User}; let name = "John";

    function greeting(){ console.log("Hello"); } class User{ constructor(name){ this.name = name;} } ES2015 export
  22. import {name, greeting, User} from "./info"; console.log(name); // John import

    * as userInfo from '/info'; console.log(userInfo.user); // John ES2015 import
  23. export default class User{ constructor(name){ this.name = name; } }

    import User from "./user“; ES2015 export, import
  24. 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 ES2015 Map
  25. 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; }} }) ES2015 Proxy console.log( dictionary['Hello'] ); // Привет console.log( dictionary['Welcome'] ); // No phrase: Welcome // Welcome
  26. 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 ES2015 Proxy
  27. 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 ES2015 Symbol