Pages

Class : this how to

Nous allons tenter de corriger le code



code à corriger !


Uncaught TypeError: Cannot read property 'somme' of undefined

Corrections

binding


  ajouter(tableau) {
      tableau.forEach(function(element) {
          this.somme += element;
           ++this.compte;
      }, this); // passage de this à forEach
   }


arrow function



  ajouter(tableau) {
      tableau.forEach((element) => {
          this.somme += element;
           ++this.compte;
      }); 
   }

La représentation schématique

let tabPers = [  {
   nom: "Dupont",
   sex : "f",
 },
 {
   nom: "Brusel",
   sex : "h",
 },
 {
   nom: "Dupont",
   sex : "f",
 },  
];

Voici la représentation de tabPers.



Donner la représentation de tabFiltre.


function femme({sex}) {
 return (sex === "f");}

function filter(array, test) {
 let passed = [];
 for (let val of array) {
   if (test(val))
     passed.push(val);
 }
 return passed;
}

let tabFiltre = filter(tabPers,femme);

Clonage en action : Object.assign

let tabPers = [  {
    nom: "Dupont",
    sex : "f",
  }, 
  {
    nom: "Brusel",
    sex : "h",
  },
  {
    nom: "Dupont",
    sex : "f",
  },  
];

let cloneTabPers = [];

for(let pers of tabPers){
  
   cloneTabPers.push(Object.assign({pays:"fr"},pers))

}




Visualisation

Besoin d'aide

arrow function !

Il fût un temps où l'on écrivait

le temps des closures


// A function that generators a new function for adding numbers
function addGenerator( num ) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function( toAdd ) {
        return num + toAdd
    };
}

// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number
var addFive = addGenerator( 5 );

// We can see here that the result of the addFive function is 9,
// when passed an argument of 4
alert( addFive( 4 ) == 9 );

le temps des blocs

let addFive_b; { let five = 5; addFive_b = function ( toAdd ) { return five + toAdd }; } console.log(addFive_b( 4 ) == 9 );

Le temps des arrow functions


ES6 arrow functions make it easy to write curried functions manually:

const add = x => y => x + y;
That means that you have to invoke add() as follows:
add(5)(4); // 9
This is currying: a function with an arity greater than one becomes a nested series of functions. Most functional programming languages with automatic currying have syntax where there is no difference between add(1, 2) and add(1)(2).


Visualisation de la fonction filtre

code