js. es6 some features

const

const Pi = 3.14;

SCOPING

block-scoped variables

// es 6
for (let i = 0; i < 10; i ++) {
  let x = i;
}

// es 5
var i;
var x;
for (i = 0; i < 10; i ++) {
    x = i;
}

block-scoped functions

// --- FUNCTION SCOPE

// es 6
{
    const f = () => 1;
    {
        const f = () => 2;
    }

}

// es 5

// hack
(function () {
    var x = 123;
})()
console.log(x); // unaccessible here

(function () {

    function f() {
        return 1
    }

    (function () {
        function f() {
            return 2
        }
    })()


})()

ARROW FUNCTIONS

arrow expressions and bodies

a.map(x => x *2)
a.forEach(x => x * 3);

this

// es6
let a = [1, 2, 3];
let b = [];
this.a.forEach(value => this.b.push(a));

// es5
var self = this;
this.a.forEach(value => self.b.push(a));

FUNCTION PARAMETERS

const f = (a = 1, b = 2) = {return a + b}; // default params
const f = (a, b, ...c){} // f (1, 2, 'hi');

SPREAD OPERATOR

const f = (a, b) => {}
const args = [1, 2];
f(...args);

f.apply(null, args);

SIMPLIFIED OBJECT DECLARATION

let x =1; 
let y = 2;
const o = {
  x,
  y,
}

// calculated property names
const o = {
['asd' + getName()]: 123
}

// method props
const o = {
 f(){},
 b(){}
}

DESTRUCTURIZATION

{a, b, c} = getObj();
let clone = {...getObj()} // clone

IMPORT / EXPORT

export const f = () => {}
...
import {f} from '';

CLASS

class myClass {
  constructor (a, b) {
    this.a = a;
    this.b = b;
  }
  do(){}
}

class myChildrenClass {
  constructor (a, b, c) {
   super(a, b);
   this.c = c 
 }
 do(){/*do smth*/ super.do() }
}

STATIC METHOD OF CLASS

class myClass {
  static do(){}
}
myClass.do();

CLASS GET / SET

class myClass {
  constructor (width, height) {
     this._width = width;
     this._height = height;
  }
  get width() {return this._width}
  set width(value) {this._width = value} 
}

let x = new myClass(1, 2);
x.width = 4;
x.height = 5;

PROMISE

const f = () => {
  return new Promise((resolve, reject) => {resolve('hi')});
}

const f = () => {
  return new Promise((resolve, reject) => {
  try {let res = await someAsyncFunc()}
  catch(e) {reject(e)}
});
}
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.