You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As we already know, functions in JavaScript are values.
4
+
Comme nous le savons déjà, les fonctions en JavaScript sont des valeurs.
5
5
6
-
Every value in JavaScript has a type. What type is a function?
6
+
Chaque valeur en JavaScript a un type. Quel type est une fonction?
7
7
8
-
In JavaScript, functions are objects.
8
+
Pour JavaScript, les fonctions sont des objets.
9
9
10
-
A good way to imagine functions is as callable "action objects". We can not only call them, but also treat them as objects: add/remove properties, pass by reference etc.
10
+
Un bon moyen d’imaginer des fonctions est en tant que des "objets d’action" qu'on peut appeler. Nous pouvons non seulement les appeler, mais aussi les traiter comme des objets: ajouter/supprimer des propriétés, passer par référence, etc.
11
11
12
+
## La propriété "name"
12
13
13
-
## The "name" property
14
+
Les objets Function contiennent quelques propriétés utilisables.
14
15
15
-
Function objects contain a few useable properties.
16
-
17
-
For instance, a function's name is accessible as the "name" property:
16
+
Par exemple, le nom d'une fonction est accessible en tant que propriété "name":
18
17
19
18
```js run
20
19
functionsayHi() {
@@ -23,30 +22,29 @@ function sayHi() {
23
22
24
23
alert(sayHi.name); // sayHi
25
24
```
26
-
27
-
What's more funny, the name-assigning logic is smart. It also assigns the correct name to functions that are used in assignments:
25
+
De plus, la logique d'attribution de nom est intelligente. Elle attribue également le nom correct aux fonctions utilisées dans les affectations:
28
26
29
27
```js run
30
28
letsayHi=function() {
31
29
alert("Hi");
32
30
}
33
31
34
-
alert(sayHi.name); // sayHi (works!)
32
+
alert(sayHi.name); // sayHi (ça marche!)
35
33
```
36
34
37
-
It also works if the assignment is done via a default value:
35
+
Cela fonctionne aussi si l’affectation est faite avec une valeur par défaut:
38
36
39
37
```js run
40
38
functionf(sayHi=function() {}) {
41
-
alert(sayHi.name); // sayHi (works!)
39
+
alert(sayHi.name); // sayHi (ça marche!)
42
40
}
43
41
44
42
f();
45
43
```
46
44
47
-
In the specification, this feature is called a "contextual name". If the function does not provide one, then in an assignment it is figured out from the context.
45
+
Dans la spécification, cette fonctionnalité est appelée "contextual name". Si la fonction n'en fournit pas, alors dans l'affectation elle est extraite du contexte.
There's no magic though. There are cases when there's no way to figure out the right name. In that case, the name property is empty, like here:
66
+
Cependant c'est pas magique. Il y a des cas où il n'y a aucun moyen de trouver le bon nom. Dans ce cas, la propriété name est vide, comme ci-dessous:
69
67
70
68
```js
71
-
//function created inside array
69
+
//fonction créée dans un tableau
72
70
let arr = [function() {}];
73
71
74
-
alert( arr[0].name ); // <empty string>
75
-
//the engine has no way to set up the right name, so there is none
72
+
alert( arr[0].name ); // <chaîne de caractères vide>
73
+
//le moteur n'a aucun moyen de définir le bon nom. Donc, il n'y en a pas
76
74
```
77
75
78
-
In practice, however, most functions do have a name.
76
+
Par contre, en pratique la plupart des fonctions ont un nom.
79
77
80
-
## The "length" property
78
+
## La propriété "length"
81
79
82
-
There is another built-in property "length" that returns the number of function parameters, for instance:
80
+
Il existe une autre propriété native, "length", qui renvoie le nombre de paramètres de la fonction, par exemple:
83
81
84
82
```js run
85
83
functionf1(a) {}
@@ -91,20 +89,20 @@ alert(f2.length); // 2
91
89
alert(many.length); // 2
92
90
```
93
91
94
-
Here we can see that rest parameters are not counted.
92
+
Nous pouvons voir que les paramètres du reste ne sont pas comptés.
95
93
96
-
The `length`property is sometimes used for introspection in functions that operate on other functions.
94
+
La propriété `length`est parfois utilisée pour l'introspection dans des fonctions qui opèrent sur d'autres fonctions.
97
95
98
-
For instance, in the code below the `ask`function accepts a `question`to ask and an arbitrary number of `handler`functions to call.
96
+
Par exemple, dans le code ci-dessous, la fonction `ask`accepte une `question`à poser et un nombre arbitraire de fonctions `handler`(gestionnaires) à appeler.
99
97
100
-
Once a user provides their answer, the function calls the handlers. We can pass two kinds of handlers:
98
+
Une fois qu'un utilisateur a fourni sa réponse, la fonction appelle les gestionnaires. Nous pouvons transmettre deux types de gestionnaires:
101
99
102
-
-A zero-argument function, which is only called when the user gives a positive answer.
103
-
-A function with arguments, which is called in either case and returns an answer.
100
+
-Une fonction sans argument, qui n'est appelée que lorsque l'utilisateur donne une réponse positive.
101
+
-Une fonction avec des arguments, appelée dans les deux cas et renvoyant une réponse.
104
102
105
-
The idea is that we have a simple, no-arguments handler syntax for positive cases (most frequent variant), but are able to provide universal handlers as well.
103
+
L'idée est que nous avons une syntaxe de gestionnaire simple, sans argument, pour les cas positifs (variante la plus fréquente), mais que nous pouvons également fournir des gestionnaires universels.
106
104
107
-
To call`handlers`the right way, we examine the `length` property:
105
+
Pour appeler`handlers`correctement, nous examinons la propriété `length`:
108
106
109
107
```js run
110
108
functionask(question, ...handlers) {
@@ -120,47 +118,46 @@ function ask(question, ...handlers) {
120
118
121
119
}
122
120
123
-
//for positive answer, both handlers are called
124
-
//for negative answer, only the second one
121
+
//pour une réponse positive, les deux gestionnaires sont appelés
122
+
//pour réponse négative, seulement le second
125
123
ask("Question?", () =>alert('You said yes'), result=>alert(result));
126
124
```
127
125
128
-
This is a particular case of so-called [polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) -- treating arguments differently depending on their type or, in our case depending on the `length`. The idea does have a use in JavaScript libraries.
126
+
Ceci est un cas particulier de ce qu'on appelle [polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) -- le traitement des arguments différemment selon leur type ou, dans notre cas, en fonction de la `length`. L'idée a une utilisation dans les bibliothèques JavaScript.
129
127
130
-
## Custom properties
128
+
## Propriétés personnalisées
131
129
132
-
We can also add properties of our own.
130
+
Nous pouvons également ajouter nos propres propriétés.
133
131
134
-
Here we add the `counter`property to track the total calls count:
132
+
Nous ajoutons ici la propriété `counter`pour suivre le nombre total d'appels:
135
133
136
134
```js run
137
135
functionsayHi() {
138
136
alert("Hi");
139
137
140
138
*!*
141
-
//let's count how many times we run
139
+
//comptons combien de fois nous executons
142
140
sayHi.counter++;
143
141
*/!*
144
142
}
145
-
sayHi.counter=0; //initial value
143
+
sayHi.counter=0; //valeur initiale
146
144
147
145
sayHi(); // Hi
148
146
sayHi(); // Hi
149
147
150
-
alert( `Called ${sayHi.counter} times` ); //Called 2 times
148
+
alert( `Called ${sayHi.counter} times` ); //Appelée 2 fois
151
149
```
152
150
153
-
```warn header="A property is not a variable"
154
-
A property assigned to a function like `sayHi.counter = 0` does *not* define a local variable `counter` inside it. In other words, a property `counter` and a variable `let counter` are two unrelated things.
151
+
```warn header="Une propriété n'est pas une variable"
152
+
Une propriété affectée à une fonction comme `sayHi.counter = 0` *ne définit pas* une variable locale `counter` à l'intérieur de celle-ci. En d'autres termes, une propriété `counter` et une variable `let counter` sont deux choses indépendantes.
155
153
156
-
We can treat a function as an object, store properties in it, but that has no effect on its execution. Variables are not function properties and vice versa. These are just parallel worlds.
154
+
On peut traiter une fonction comme un objet, y stocker des propriétés, mais cela n’a aucun effet sur son exécution. Les variables ne sont pas des propriétés de fonction et inversement. Ce sont des mondes parallèles.
157
155
```
158
-
159
-
Function properties can replace closures sometimes. For instance, we can rewrite the counter function example from the chapter <info:closure> to use a function property:
156
+
Les propriétés de fonction peuvent parfois remplacer les fermetures. Par exemple, nous pouvons réécrire l’exemple de fonction de compteur du chapitre <info:fermeture> pour utiliser une propriété de fonction:
160
157
161
158
```js run
162
159
functionmakeCounter() {
163
-
//instead of:
160
+
//au lieu de:
164
161
// let count = 0
165
162
166
163
functioncounter() {
@@ -177,11 +174,11 @@ alert( counter() ); // 0
177
174
alert( counter() ); // 1
178
175
```
179
176
180
-
The`count`is now stored in the function directly, not in its outer Lexical Environment.
177
+
Le`count`est maintenant stocké dans la fonction directement, pas dans son environnement lexical externe
181
178
182
-
Is it better or worse than using a closure?
179
+
Est-ce meilleur ou pire que d'utiliser une fermeture?
183
180
184
-
The main difference is that if the value of`count`lives in an outer variable, then external code is unable to access it. Only nested functions may modify it. And if it's bound to a function, then such a thing is possible:
181
+
La principale différence est que si la valeur de`count`réside dans une variable externe, le code externe ne peut pas y accéder. Seules les fonctions imbriquées peuvent le modifier. Et si c'est lié à une fonction, une telle chose est possible:
185
182
186
183
```js run
187
184
functionmakeCounter() {
@@ -203,35 +200,35 @@ alert( counter() ); // 10
203
200
*/!*
204
201
```
205
202
206
-
So the choice of implementation depends on our aims.
203
+
Le choix dépend donc de nos objectifs.
207
204
208
-
## Named Function Expression
205
+
## Expression de fonction nommée
209
206
210
-
Named Function Expression, or NFE, is a term for Function Expressions that have a name.
207
+
Expression de fonction nommée, ou EFN, est un terme pour les expressions de fonction qui ont un nom.
211
208
212
-
For instance, let's take an ordinary Function Expression:
209
+
Par exemple, prenons une expression de fonction ordinaire:
213
210
214
211
```js
215
212
letsayHi=function(who) {
216
213
alert(`Hello, ${who}`);
217
214
};
218
215
```
219
216
220
-
And add a name to it:
217
+
Et ajoutons un nom à cela:
221
218
222
219
```js
223
220
letsayHi=function*!*func*/!*(who) {
224
221
alert(`Hello, ${who}`);
225
222
};
226
223
```
227
224
228
-
Did we achieve anything here? What's the purpose of that additional `"func"` name?
225
+
Avons-nous réalisé quelque chose ici? Quel est le but de ce nom supplémentaire `"func"`?
229
226
230
-
First let's note, that we still have a Function Expression. Adding the name`"func"`after`function`did not make it a Function Declaration, because it is still created as a part of an assignment expression.
227
+
Notons d'abord que nous avons toujours une expression de fonction. L'ajout du nom`"func"`après`function`n'en a pas fait une déclaration de fonction, car il est toujours créé dans le cadre d'une expression d'affectation.
231
228
232
-
Adding such a name also did not break anything.
229
+
L'ajout d'un tel nom n'a également rien cassé.
233
230
234
-
The function is still available as`sayHi()`:
231
+
La fonction est toujours disponible sous la forme`sayHi()`:
235
232
236
233
```js run
237
234
letsayHi=function*!*func*/!*(who) {
@@ -241,34 +238,34 @@ let sayHi = function *!*func*/!*(who) {
241
238
sayHi("John"); // Hello, John
242
239
```
243
240
244
-
There are two special things about the name `func`:
241
+
Le nom `func` a deux particularités:
245
242
246
-
1.It allows the function to reference itself internally.
247
-
2.It is not visible outside of the function.
243
+
1.Il permet à la fonction de se référencer en interne.
244
+
2.Il n'est pas visible en dehors de la fonction.
248
245
249
-
For instance, the function`sayHi`below calls itself again with`"Guest"`if no`who`is provided:
246
+
Par exemple, la fonction`sayHi`ci-dessous s’appelle à nouveau avec`"Guest"`si aucun`who`est fourni:
250
247
251
248
```js run
252
249
letsayHi=function*!*func*/!*(who) {
253
250
if (who) {
254
251
alert(`Hello, ${who}`);
255
252
} else {
256
253
*!*
257
-
func("Guest"); //use func to re-call itself
254
+
func("Guest"); //utilise func pour se rappeler
258
255
*/!*
259
256
}
260
257
};
261
258
262
259
sayHi(); // Hello, Guest
263
260
264
-
//But this won't work:
265
-
func(); // Error, func is not defined (not visible outside of the function)
261
+
//Mais ceci ne marchera pas:
262
+
func(); // Error, func is not defined (pas visible à l'extérieur de la fonction)
266
263
```
267
264
268
-
Why do we use `func`? Maybe just use`sayHi`for the nested call?
The problem with that code is that the value of`sayHi`may change. The function may go to another variable, and the code will start to give errors:
282
+
Le problème avec ce code est que la valeur de`sayHi`peut changer. La fonction peut aller à une autre variable et le code va commencer à donner des erreurs:
286
283
287
284
```js run
288
285
letsayHi=function(who) {
@@ -298,55 +295,55 @@ let sayHi = function(who) {
298
295
let welcome = sayHi;
299
296
sayHi =null;
300
297
301
-
welcome(); // Error, the nested sayHi call doesn't work any more!
298
+
welcome(); // Error, l'appel sayHi imbriqué ne fonctionne plus!
302
299
```
303
300
304
-
That happens because the function takes `sayHi`from its outer lexical environment. There's no local `sayHi`, so the outer variable is used. And at the moment of the call that outer `sayHi`is`null`.
301
+
Cela se produit parce que la fonction tire `sayHi`de son environnement lexical externe. Il n'y a pas de `sayHi` local, donc la variable externe est utilisée. Et au moment de l'appel, cet `sayHi`extérieur est`null`.
305
302
306
-
The optional name which we can put into the Function Expression is meant to solve exactly these kinds of problems.
303
+
Le nom optionnel que nous pouvons mettre dans l’expression de fonction est destiné à résoudre exactement ce type de problèmes.
Now it works, because the name `"func"` is function-local. It is not taken from outside (and not visible there). The specification guarantees that it will always reference the current function.
324
+
Maintenant cela fonctionne, car le nom `'func'` est local à la fonction. Il n'est pas pris de l'extérieur (et non visible là-bas). La spécification garantit qu'elle fera toujours référence à la fonction actuelle.
328
325
329
-
The outer code still has it's variable `sayHi`or`welcome`. And`func`is an "internal function name", how the function can call itself internally.
326
+
Le code externe a toujours sa variable `sayHi`ou`welcome`. Et`func`est un "nom de fonction interne", c'est comment la fonction peut s'appeler en interne.
330
327
331
-
```smart header="There's no such thing for Function Declaration"
332
-
The "internal name" feature described here is only available for Function Expressions, not to Function Declarations. For Function Declarations, there's just no syntax possibility to add a one more "internal" name.
328
+
```smart header="Il n'y a rien de tel pour la déclaration de fonction"
329
+
La fonctionnalité "nom interne" décrite ici n'est disponible que pour les expressions de fonction, pas pour les déclarations de fonction. Pour les déclarations de fonctions, il n’y a aucune possibilité de syntaxe d’ajouter un nom "interne" supplémentaire.
333
330
334
-
Sometimes, when we need a reliable internal name, it's the reason to rewrite a Function Declaration to Named Function Expression form.
331
+
Parfois, lorsque nous avons besoin d’un nom interne fiable, c’est la raison pour laquelle nous réécrivons une déclaration de fonction en tant qe'expression de fonction nommée.
335
332
```
336
333
337
-
## Summary
334
+
## Résumé
338
335
339
-
Functions are objects.
336
+
Les fonctions sont des objets.
340
337
341
-
Here we covered their properties:
338
+
Ici nous avons couvert leurs propriétés:
342
339
343
-
-`name` -- the function name. Usually taken from the function definition, but if there's none, JavaScript tries to guess it from the context (e.g. an assignment).
344
-
-`length` -- the number of arguments in the function definition. Rest parameters are not counted.
340
+
-`name` - le nom de la fonction. Habituellement tiré de la définition de la fonction, mais s’il n’en existe pas, JavaScript essaie de le deviner à partir du contexte (par exemple, une affectation).
341
+
-`length` - le nombre d'arguments dans la définition de la fonction. Les paramètres du reste ne sont pas comptés.
345
342
346
-
If the function is declared as a Function Expression (not in the main code flow), and it carries the name, then it is called a Named Function Expression. The name can be used inside to reference itself, for recursive calls or such.
343
+
Si la fonction est déclarée en tant qu'expression de fonction (et non dans le flux du code principal) et qu'elle porte `name`, elle est appelée expression de fonction nommée. Le nom peut être utilisé à l'intérieur pour se référencer, pour des appels récursifs ou autres.
347
344
348
-
Also, functions may carry additional properties. Many well-known JavaScript libraries make great use of this feature.
345
+
De plus, les fonctions peuvent avoir des propriétés supplémentaires. De nombreuses bibliothèques JavaScript bien connues font bon usage de cette fonctionnalité.
349
346
350
-
They create a "main" function and attach many other "helper" functions to it. For instance, the [jquery](https://jquery.com)library creates a function named `$`. The [lodash](https://lodash.com)library creates a function `_`. And then adds`_.clone`,`_.keyBy`and other properties to (see the [docs](https://lodash.com/docs)when you want learn more about them). Actually, they do it to lessen their pollution of the global space, so that a single library gives only one global variable. That reduces the possibility of naming conflicts.
347
+
Ils créent une fonction "principale" et y attachent de nombreuses autres fonctions "d'assistance". Par exemple, la bibliothèque [jquery](https://jquery.com) crée une fonction nommée `$`. La bibliothèque [lodash](https://lodash.com) crée une fonction `_`. Et ajoute ensuite`_.clone`,`_.keyBy`et d'autres propriétés (voir [docs](https://lodash.com/docs) lorsque vous souhaitez en savoir plus à leur sujet). En fait, ils le font pour réduire leur pollution de l'espace global, de sorte qu'une seule bibliothèque ne donne qu'une seule variable globale. Cela réduit la possibilité de conflits de noms.
351
348
352
-
So, a function can do a useful job by itself and also carry a bunch of other functionality in properties.
349
+
Ainsi, une fonction peut faire un travail utile par elle-même et aussi porter un tas d’autres fonctionnalités dans les propriétés.
0 commit comments