◐ Shell
clean mode source ↗

Function object, NFE (Tasks) by TevaHenry · Pull Request #36 · javascript-tutorial/fr.javascript.info

@@ -1,9 +1,9 @@
1. For the whole thing to work *anyhow*, the result of `sum` must be function. 2. That function must keep in memory the current value between calls. 3. According to the task, the function must become the number when used in `==`. Functions are objects, so the conversion happens as described in the chapter <info:object-toprimitive>, and we can provide our own method that returns the number. 1. Pour que tout fonctionne * de toute façon *, le résultat de `sum` doit être fonction. 2. Cette fonction doit garder en mémoire la valeur actuelle entre les appels. 3. Selon la tâche, la fonction doit devenir le numéro lorsqu'elle est utilisée dans `==`. Les fonctions étant des objets, la conversion s'effectue comme décrit dans le chapitre <info:object-toprimitive>, et nous pouvons fournir notre propre méthode qui renvoie le nombre.
Now the code: Maintenant le code:
```js run function sum(a) { Expand All @@ -28,28 +28,28 @@ alert( sum(6)(-1)(-2)(-3) ); // 0 alert( sum(0)(1)(2)(3)(4)(5) ); // 15 ```
Please note that the `sum` function actually works only once. It returns function `f`. Veuillez noter que la fonction `sum` ne fonctionne réellement qu'une fois. Il renvoie la fonction `f`.
Then, on each subsequent call, `f` adds its parameter to the sum `currentSum`, and returns itself. Ensuite, à chaque appel suivant, `f` ajoute son paramètre à la somme `currentSum`, et se renvoie lui-même.
**There is no recursion in the last line of `f`.** **Il n'y a pas de récursion dans la dernière ligne de `f`.**
Here is what recursion looks like: Voici à quoi ressemble la récursion:
```js function f(b) { currentSum += b; return f(); // <-- recursive call return f(); // <-- appel récursif } ```
And in our case, we just return the function, without calling it: Et dans notre cas, nous renvoyons simplement la fonction, sans l'appeler:
```js function f(b) { currentSum += b; return f; // <-- does not call itself, returns itself return f; // <-- ne s'appelle pas, se renvoie } ```
This `f` will be used in the next call, again return itself, so many times as needed. Then, when used as a number or a string -- the `toString` returns the `currentSum`. We could also use `Symbol.toPrimitive` or `valueOf` here for the conversion. Ce `f` sera utilisé lors du prochain appel et se renvera lui-même autant de fois que nécessaire. Ensuite, lorsqu'il est utilisé sous forme de nombre ou de chaîne, le `toString` renvoie le `currentSum`. Nous pourrions aussi utiliser `Symbol.toPrimitive` ou` valueOf` ici pour la conversion.