Skip to content

Commit 6b63783

Browse files
authored
Merge pull request #498 from benjGam/feature/tra-func-binding
Translate Functions Binding (EN -> FR)
2 parents 025b453 + 7d0a1a2 commit 6b63783

File tree

1 file changed

+78
-77
lines changed

1 file changed

+78
-77
lines changed

1-js/06-advanced-functions/10-bind/article.md

Lines changed: 78 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@ libs:
33

44
---
55

6-
# Function binding
6+
# Le "bind" de fonction
77

8-
When passing object methods as callbacks, for instance to `setTimeout`, there's a known problem: "losing `this`".
8+
Lorsque l'on transmet des méthodes objets en tant que callbacks, par exemple à `setTimeout`, il y a un problème connu : "la perte du `this`".
99

10-
In this chapter we'll see the ways to fix it.
10+
Dans ce chapitre nous verrons les façons de régler ça.
1111

12-
## Losing "this"
12+
## La perte du "this"
1313

14-
We've already seen examples of losing `this`. Once a method is passed somewhere separately from the object -- `this` is lost.
14+
Nous avons déjà vu des exemples de la perte du `this`. Une fois qu'une méthode est passée quelque part séparement de l'objet -- `this` est perdu.
1515

16-
Here's how it may happen with `setTimeout`:
16+
Voici comment cela pourrait arriver avec `setTimeout` :
1717

1818
```js run
1919
let user = {
@@ -28,22 +28,23 @@ setTimeout(user.sayHi, 1000); // Hello, undefined!
2828
*/!*
2929
```
3030

31-
As we can see, the output shows not "John" as `this.firstName`, but `undefined`!
31+
Comme nous pouvons le voir, la sortie n'affiche pas "John" pour `this.firstName`, mais `undefined` !
3232

33-
That's because `setTimeout` got the function `user.sayHi`, separately from the object. The last line can be rewritten as:
33+
C'est car `setTimeout` a eu la fonction `user.sayHi`, séparement de l'objet. La dernière ligne pourrait être réécrite comme :
3434

3535
```js
3636
let f = user.sayHi;
37-
setTimeout(f, 1000); // lost user context
37+
setTimeout(f, 1000); // Perte du contexte d'user
3838
```
3939

40-
The method `setTimeout` in-browser is a little special: it sets `this=window` for the function call (for Node.js, `this` becomes the timer object, but doesn't really matter here). So for `this.firstName` it tries to get `window.firstName`, which does not exist. In other similar cases, usually `this` just becomes `undefined`.
40+
La méthode `setTimeout` dans le navigateur est un peu spéciale : elle définit `this=window` pour l'appel à la fonction (pour Node.js, `this` devient un objet "timer", mais ça n'a pas d'importance ici). Donc pour `this.firstName` il essaye de récuperer `window.firstName`, qui n'existe pas. Dans d'autres cas similaires, `this` devient généralement `undefined`.
4141

42-
The task is quite typical -- we want to pass an object method somewhere else (here -- to the scheduler) where it will be called. How to make sure that it will be called in the right context?
42+
Cette tâche est plutôt commune -- on veut transmettre une méthode objet quelque part ailleurs (ici -- au scheduler) où elle sera appelée.
43+
Comment s'assurer qu'elle sera appelée dans le bon contexte ?
4344

44-
## Solution 1: a wrapper
45+
## Solution 1 : Un wrapper
4546

46-
The simplest solution is to use a wrapping function:
47+
La solution la plus simple est d'utiliser une fonction enveloppée :
4748

4849
```js run
4950
let user = {
@@ -60,18 +61,17 @@ setTimeout(function() {
6061
*/!*
6162
```
6263

63-
Now it works, because it receives `user` from the outer lexical environment, and then calls the method normally.
64+
Maintenant ça fonctionne, car elle reçoit `user` depuis un environnement lexical extérieur, et donc les appels à la fonction se font normalement.
6465

65-
The same, but shorter:
66+
La même chose mais en plus court :
6667

6768
```js
6869
setTimeout(() => user.sayHi(), 1000); // Hello, John!
6970
```
7071

71-
Looks fine, but a slight vulnerability appears in our code structure.
72-
73-
What if before `setTimeout` triggers (there's one second delay!) `user` changes value? Then, suddenly, it will call the wrong object!
72+
Ça à l'air bon, mais une légère vulnérabilité apparaît dans la structure de notre code.
7473

74+
Que se passe t-il si avant le déclenchement de `setTimeout` (il y une seconde de délai) `user` changeait de valeur ? Alors, soudainement, ça appelera le mauvais objet !
7575

7676
```js run
7777
let user = {
@@ -83,32 +83,32 @@ let user = {
8383

8484
setTimeout(() => user.sayHi(), 1000);
8585

86-
// ...the value of user changes within 1 second
86+
// ...La valeur d'user dans 1 seconde
8787
user = {
8888
sayHi() { alert("Another user in setTimeout!"); }
8989
};
9090

91-
// Another user in setTimeout!
91+
// Un autre user est dans le setTimeout !
9292
```
9393

94-
The next solution guarantees that such thing won't happen.
94+
La prochaine solution garantit que ce genre de chose n'arrivera pas
9595

96-
## Solution 2: bind
96+
## Solution 2 : "bind"
9797

98-
Functions provide a built-in method [bind](mdn:js/Function/bind) that allows to fix `this`.
98+
Les fonctions fournissent une méthode intégrée, [bind](mdn:js/Function/bind) qui permet de corriger `this`.
9999

100-
The basic syntax is:
100+
La syntaxe basique est :
101101

102102
```js
103-
// more complex syntax will come a little later
103+
// Une syntaxe plus complexe arrivera bientot
104104
let boundFunc = func.bind(context);
105105
```
106106

107-
The result of `func.bind(context)` is a special function-like "exotic object", that is callable as function and transparently passes the call to `func` setting `this=context`.
107+
Le résultat de `func.bind(context)` est une "objet exotique" dans le style d'une fonction, qui est appellable comme une fonction et qui transmet l'appel à `func` en définissant `this=context` de façon transparente.
108108

109-
In other words, calling `boundFunc` is like `func` with fixed `this`.
109+
En d'autres termes, appeller `boundFunc` équivaut à `func` avec un `this` corrigé.
110110

111-
For instance, here `funcUser` passes a call to `func` with `this=user`:
111+
Par exemple, ici `funcUser` passe l'appel à `this` tel que `this=user` :
112112

113113
```js run
114114
let user = {
@@ -125,9 +125,9 @@ funcUser(); // John
125125
*/!*
126126
```
127127

128-
Here `func.bind(user)` as a "bound variant" of `func`, with fixed `this=user`.
128+
Ici `func.bind(user)` en tant "variante liée" de `func`, avec `this=user`.
129129

130-
All arguments are passed to the original `func` "as is", for instance:
130+
Tous les arguments sont passés à l'originale `func` "tels quels", par exemple :
131131

132132
```js run
133133
let user = {
@@ -138,15 +138,15 @@ function func(phrase) {
138138
alert(phrase + ', ' + this.firstName);
139139
}
140140

141-
// bind this to user
141+
// Lie this à user
142142
let funcUser = func.bind(user);
143143

144144
*!*
145-
funcUser("Hello"); // Hello, John (argument "Hello" is passed, and this=user)
145+
funcUser("Hello"); // Hello, John (l'argument "Hello" est passé, et this=user)
146146
*/!*
147147
```
148148

149-
Now let's try with an object method:
149+
Maintenant essayons avec une méthode objet :
150150

151151

152152
```js run
@@ -161,21 +161,21 @@ let user = {
161161
let sayHi = user.sayHi.bind(user); // (*)
162162
*/!*
163163

164-
// can run it without an object
164+
// Peut s'exécuter sans objet
165165
sayHi(); // Hello, John!
166166

167167
setTimeout(sayHi, 1000); // Hello, John!
168168

169-
// even if the value of user changes within 1 second
170-
// sayHi uses the pre-bound value which is reference to the old user object
169+
// Mème si la valeur de user change dans 1 seconde
170+
// sayHi utilise la valeur pré-liée, laquelle fait référence à l'ancien objet user
171171
user = {
172172
sayHi() { alert("Another user in setTimeout!"); }
173173
};
174174
```
175175

176-
In the line `(*)` we take the method `user.sayHi` and bind it to `user`. The `sayHi` is a "bound" function, that can be called alone or passed to `setTimeout` -- doesn't matter, the context will be right.
176+
Sur la ligne `(*)` nous prenons la méthode `user.sayHi` en nous la lions à `user`. La méthode `sayHi` est une fonction "liée", qui peut être appelée seule ou être transmise à `setTimeout` -- ça n'a pas d'importance, le contexte sera le bon.
177177

178-
Here we can see that arguments are passed "as is", only `this` is fixed by `bind`:
178+
Ici, nous pouvons voir que les arguments passés "tels quels", seulement `this` est corrigé par `bind` :
179179

180180
```js run
181181
let user = {
@@ -187,12 +187,12 @@ let user = {
187187

188188
let say = user.say.bind(user);
189189

190-
say("Hello"); // Hello, John! ("Hello" argument is passed to say)
191-
say("Bye"); // Bye, John! ("Bye" is passed to say)
190+
say("Hello"); // Hello, John! (l'argument "Hello" est passé à say)
191+
say("Bye"); // Bye, John! (l'argument "Bye" est passé à say)
192192
```
193193

194-
````smart header="Convenience method: `bindAll`"
195-
If an object has many methods and we plan to actively pass it around, then we could bind them all in a loop:
194+
````smart header="La méthode pratique : `bindAll`"
195+
Si un objet a plusieurs méthodes et que nous prévoyons de le transmettre plusieurs fois, alors on pourrait toutes les lier dans une boucle :
196196

197197
```js
198198
for (let key in user) {
@@ -202,32 +202,32 @@ for (let key in user) {
202202
}
203203
```
204204

205-
JavaScript libraries also provide functions for convenient mass binding , e.g. [_.bindAll(object, methodNames)](https://lodash.com/docs#bindAll) in lodash.
205+
Les librairies JavaScript fournissent aussi des fonctions pratiques pour les liaisons de masse, e.g. [_.bindAll(object, methodNames)](https://lodash.com/docs#bindAll) avec lodash.
206206
````
207207
208-
## Partial functions
208+
## Les fonctions partielles
209209
210-
Until now we have only been talking about binding `this`. Let's take it a step further.
210+
Jusqu'à maintenant nous avons parlé uniquement de lier `this`. Allons plus loin.
211211
212-
We can bind not only `this`, but also arguments. That's rarely done, but sometimes can be handy.
212+
Nous pouvons lier `this`, mais aussi des arguments. C'est rarement utilisé, mais ça peut être pratique.
213213
214-
The full syntax of `bind`:
214+
La syntaxe complète de `bind` :
215215
216216
```js
217217
let bound = func.bind(context, [arg1], [arg2], ...);
218218
```
219219
220-
It allows to bind context as `this` and starting arguments of the function.
220+
Elle permet de lier le contexte en tant que `this` et de démarrer les arguments de la fonction.
221221
222-
For instance, we have a multiplication function `mul(a, b)`:
222+
Par exemple, nous avons une fonction de multiplication `mul(a, b)` :
223223
224224
```js
225225
function mul(a, b) {
226226
return a * b;
227227
}
228228
```
229229
230-
Let's use `bind` to create a function `double` on its base:
230+
Utilisons `bind` pour créer une fonction `double` sur cette base :
231231
232232
```js run
233233
function mul(a, b) {
@@ -243,13 +243,13 @@ alert( double(4) ); // = mul(2, 4) = 8
243243
alert( double(5) ); // = mul(2, 5) = 10
244244
```
245245
246-
The call to `mul.bind(null, 2)` creates a new function `double` that passes calls to `mul`, fixing `null` as the context and `2` as the first argument. Further arguments are passed "as is".
246+
L'appel à `mul.bind(null, 2)` créer une nouvelle fonction `double` qui transmet les appels à `mul`, corrigeant `null` dans le contexte et `2` comme premier argument. Les arguments sont passés "tels quels" plus loin.
247247
248-
That's called [partial function application](https://en.wikipedia.org/wiki/Partial_application) -- we create a new function by fixing some parameters of the existing one.
248+
Ça s'appelle [l'application de fonction partielle](https://en.wikipedia.org/wiki/Partial_application) -- nous créeons une nouvelle fonction en corrigeant certains paramètres d'une fonction existante.
249249
250-
Please note that we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`.
250+
Veuillez noter que nous n'utilisons actuellement pas `this` ici. Mais `bind` en a besoin, donc nous devrions mettre quelque chose dedans comme `null`.
251251
252-
The function `triple` in the code below triples the value:
252+
La fonction `triple` dans le code ci-dessous triple la valeur :
253253
254254
```js run
255255
function mul(a, b) {
@@ -265,23 +265,24 @@ alert( triple(4) ); // = mul(3, 4) = 12
265265
alert( triple(5) ); // = mul(3, 5) = 15
266266
```
267267
268-
Why do we usually make a partial function?
268+
Pourquoi faisons nous généralement une fonction partielle ?
269269
270-
The benefit is that we can create an independent function with a readable name (`double`, `triple`). We can use it and not provide the first argument every time as it's fixed with `bind`.
270+
L'avantage de faire ça est que nous pouvons créer une fonction indépendante avec un nom lisible (`double`, `triple`). Nous pouvons les utiliser et ne pas fournir de premier argument à chaque fois puisque c'est corrigé par `bind`.
271271
272-
In other cases, partial application is useful when we have a very generic function and want a less universal variant of it for convenience.
272+
Dans d'autres cas, les fonctions partielles sont utiles quand nous avons des fonctions vraiment génériques et que nous voulons une variante moins universelle pour des raisons pratiques.
273273
274-
For instance, we have a function `send(from, to, text)`. Then, inside a `user` object we may want to use a partial variant of it: `sendTo(to, text)` that sends from the current user.
274+
Par exemple, nous avons une fonction `send(from, to, text)`. Alors, dans un objet `user` nous pourrions vouloir en utiliser une variante partielle : `sendTo(to, text)` qui envoie depuis l'utilisateur actuel.
275275
276-
## Going partial without context
276+
## Aller dans les partielles sans contexte
277277
278-
What if we'd like to fix some arguments, but not the context `this`? For example, for an object method.
278+
Que se passerait t-il si nous voulions corriger certains arguments, mais pas le contexte `this` ?
279+
Par exemple, pour une méthode objet.
279280
280-
The native `bind` does not allow that. We can't just omit the context and jump to arguments.
281+
La fonction `bind` native ne permet pas ça. Nous ne pouvons pas juste omettre le contexte et aller directement aux arguments.
281282
282-
Fortunately, a function `partial` for binding only arguments can be easily implemented.
283+
Heureusement, une fonction `partial` pour lier seulement les arguments peut être facilement implémentée.
283284
284-
Like this:
285+
Comme ça :
285286
286287
```js run
287288
*!*
@@ -292,37 +293,37 @@ function partial(func, ...argsBound) {
292293
}
293294
*/!*
294295
295-
// Usage:
296+
// Utilisation :
296297
let user = {
297298
firstName: "John",
298299
say(time, phrase) {
299300
alert(`[${time}] ${this.firstName}: ${phrase}!`);
300301
}
301302
};
302303
303-
// add a partial method with fixed time
304+
// Ajoute une méthode partielle avec time corrigé
304305
user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes());
305306
306307
user.sayNow("Hello");
307-
// Something like:
308+
// Quelque chose du genre :
308309
// [10:00] John: Hello!
309310
```
310311
311-
The result of `partial(func[, arg1, arg2...])` call is a wrapper `(*)` that calls `func` with:
312-
- Same `this` as it gets (for `user.sayNow` call it's `user`)
313-
- Then gives it `...argsBound` -- arguments from the `partial` call (`"10:00"`)
314-
- Then gives it `...args` -- arguments given to the wrapper (`"Hello"`)
312+
Le résultat de l'appel `partial(func[, arg1, arg2...])` est une enveloppe `(*)` qui appelle `func` avec :
313+
- Le même `this` qu'il récupère (pour `user.sayNow` l'appel est `user`)
314+
- Alors il donne `...argsBound` -- les arguments provenant de l'appel de `partial` (`"10:00"`)
315+
- Alors il donne `...args` -- les arguments donnés à l'enveloppe (`"Hello"`)
315316
316-
So easy to do it with the spread syntax, right?
317+
Alors, c'est simple à faire avec la spread syntaxe, pas vrai ?
317318
318-
Also there's a ready [_.partial](https://lodash.com/docs#partial) implementation from lodash library.
319+
Aussi il y a une implémentation de [_.partial](https://lodash.com/docs#partial) prête à l'emploi dans les librairies lodash.
319320
320-
## Summary
321+
## Résumé
321322
322-
Method `func.bind(context, ...args)` returns a "bound variant" of function `func` that fixes the context `this` and first arguments if given.
323+
La méthode `func.bind(context, ...args)` retourne une "variante liée" de la fonction `func` qui corrige le contexte de `this` et des premiers arguments s'ils sont donnés.
323324
324-
Usually we apply `bind` to fix `this` for an object method, so that we can pass it somewhere. For example, to `setTimeout`.
325+
Nous appliquons généralement `bind` pour corriger `this` pour une méthode objet, comme ça nous pouvons la passer ailleurs. Par exemple, à `setTimeout`.
325326
326-
When we fix some arguments of an existing function, the resulting (less universal) function is called *partially applied* or *partial*.
327+
Quand nous corrigeons certains arguments d'une fonction existante, la fonction (moins universelle) en résultant est dite *partiellement appliquée* ou *partielle*.
327328
328-
Partials are convenient when we don't want to repeat the same argument over and over again. Like if we have a `send(from, to)` function, and `from` should always be the same for our task, we can get a partial and go on with it.
329+
Les fonctions partielles sont pratiques quand nous ne voulons pas répéter le même argument encore et encore. Comme si nous avions une fonction `send(from, to)`, et que `from` devait être toujours le même pour notre tâche, nous pourrions récupérer une partielle et continuer.

0 commit comments

Comments
 (0)