Aller au contenu

Langage avancé ES6

Beaucoup de nouvelles choses dans cette version majeure d’ECMAScript. Voici les plus intéressantes :

Constantes et variables scopées#

// constantes
const PI = 3.141592654;

// scoped variable
for (let i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i); // undefined

Arrow functions#

[0,1,2].map(function (el) {
  return el + 2;
});
// ===
[0,1,2].map(el => el + 2);


// avec corps de fonction
[0,1,2,3,4].map(el => {
  if (el < 3) {
    return el;
  }
});

Le this est bindé automatiquement. Regardez cet exemple, deux fonctions, et pourtant deux this différents

function Personne() {
  let f1 = function () { /* this = Window */ };
  let f2 = () => { /* this = Personne */ };
}
function Foo () {
  [0,1,2].forEach(() => {
    // this = f
  });
}
let f = new Foo();

Paramètres#

// par défaut
function foo (a = 42) {
  return a;
}

// rest (aggregation)
function foo (a, ...b) {
  return b.join(' ') + ' ' + a;
}
foo(42, 'Hello', 'World'); // Hello World 42

Template string#

let foo = { bar: 42 };
console.log(`Hello ${foo.bar}`);

Objects#

// proprietes
let x = 0;
let y = 0;
let p = {x, y}; // == let p = { x: x, y: y}

// destructuring
let {width, height} = el.getBoudingClientRect();
// width = el.getBoudingClientRect().width, height = el.getBoudingClientRect().height

let [a, b, c] = [0, 1, 2];
// a = 0, b = 1, c = 2

// permutation
let a = [0, 1, 2];
let b = [3, 4, 5];
[a, b] = [b, a];
// a = [3, 4, 5], b = [0, 1, 2]

// spread
let a = [0, 1, 2];
let b = [...a, 3, 4, 5]; // [0, 1, 2, 3, 4, 5]

// conversion d’array-like
let els = document.querySelectorAll('div');
[...els].map(el => { console.log(el) });

// méthodes comme propriétés
let foo = {
  bar () {
    return 42;
  }
};
// foo.bar()

Modules#

// lib/math.js
export const PI = 3.141592654;
export const E = 2.71828182846;

// main.js
import { PI, E } from 'lib/math.js';
console.log(PI, E);

// default export
// lib/math/sum.js
export default function sum (...a) {
  return a.reduce((sum, val) => sum + val);
}

// main.js
import somme from 'lib/math/sum.js';
console.log(somme(2,5,8,3)); // 18

Classes#

Les classes JS ne sont qu’une écriture simplifiée du concept d’héritage par prototype.

class Point {
  constructor (x, y) {
    this.x = x;
    this.y = y;
  }
  distance (point) {
    return Math.sqrt(Math.pow(this.x - point.x, 2) + Math.pow(this.y - point.y, 2));
  }
}

// héritage
class Point3D extends Point {
  constructor (x, y, z) {
    super(x, y);
    this.z = z;
  }
  distance3D (point) {
    return Math.sqrt(Math.pow(this.distance(point), 2) + Math.pow(this.z - point.z, 2));
  }
}
let p1 = new Point3D(0, 0, 0);
let p2 = new Point3D(1, 1, 1);
p1.distance(p2); // 1.414
p1.distance3D(p2); // 1.732

Et pleins d’autres choses encore : http://es6-features.org

Attention au support navigateur. Pour vous aider :