ES 2015

Nov 7th 2018 by Nicolas Zozol

ES2015 and a bit of ES2017


ES 2015

var, let, const;

  • var : variable javascript classique
  • let : scope plus logique
  • const : la variable ne peut remodifiée

Classes

    export class DataService extends Service{
    
        constructor(root){
            super(root); // call to super
            this.api = 'root/api';
        }
    
        fetchUsers() {        
            return axios.get(`${this.api}/users/`)
                .then(resp=>resp.data)
                .catch(err => alert(err));
        }
    }

String templates

  • Permet de faire du multiligne (templates !)
    const template = `        
    <div class="main-header">This is a Main header toolbar</div>
    <div class="side-plus-content">        
        <div class="sidebar">
            <sidebar>this is the sidebar</sidebar>
        </div>        
    </div> `;

String template et variable

Permet d'insérer une variable


class AdminService{

getAdmin (id : number) { return axios.get(/api/admins/${id}) //insert id .then(response => response.data); }
}

Fonctions courtes

  • une seule ligne : return facultatif
    let add = (x, y) => x + y;
    
  • un seul paramètre: parenthèse facultative

    let square = x => x * x
    

Binding

  • Fonction bindée à this
  • Plus besoin de var that = this
    // binding
    class AdminService{               
                
        display(e){alert(e);}
        
        getAdmin (id : number) {
            return axios.get(`/api/admins/${id}`)
                .then(response => response.data);
                .catch(err=> this.display(err) ) // this === instance
        }        
    }
    
    

Array splats

    const x = [2,4,6];
    
    // new object with splats
    const y = [...x, 8];
    
    // assigment by destructuration
    const [a,b,c]=x;
    console.log(a, b, c); //2, 4, 6
    

ES 2017 (or later)

Object splats

    const x = {a:2, b:4};
    const y = {b:0, c:4};
    const z = {...x, ...y, d:6}; 
    console.log(z.b); //0
    
    // assigment by destructuration
    let {a,b}=x;
    console.log(a, b);

Paramètre de classe

export class ViewChild {

  id=12;   // not in ES2015

  constructor() { }
}

Decorator

    function nice(target:any){
        target.beautiful=true;
        target.color='red';
    }
    
    @nice
    class People{
        constructor(public name: string){}        
    }

    new People().color === 'red';

Share this post

Nicolas Zozol

Former science teacher, almost serial entrepreneur and currently hard-core coder