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
The `"prototype"`property is widely used by the core of JavaScript itself. All built-in constructor functions use it.
3
+
La propriété `"prototype"`est largement utilisée au centre de JavaScript lui-même. Toutes les fonctions constructeurs intégrées l'utilisent.
4
4
5
-
First we'll see at the details, and then how to use it for adding new capabilities to built-in objects.
5
+
Nous verrons d’abord les détails, puis comment l’utiliser pour ajouter de nouvelles fonctionnalités aux objets intégrés.
6
6
7
7
## Object.prototype
8
8
9
-
Let's say we output an empty object:
9
+
Disons que nous produisons un objet vide:
10
10
11
11
```js run
12
12
let obj = {};
13
13
alert( obj ); // "[object Object]" ?
14
14
```
15
15
16
-
Where's the code that generates the string`"[object Object]"`? That's a built-in`toString`method, but where is it? The`obj`is empty!
16
+
Où est le code qui génère la chaîne`"[object Object]"`? C'est une méthode`toString`intégrée, mais où est-elle? Le`obj`est vide!
17
17
18
-
...But the short notation `obj = {}`is the same as `obj = new Object()`, where`Object`is a built-in object constructor function, with its own`prototype`referencing a huge object with`toString`and other methods.
18
+
...Mais la notation abrégée `obj = {}`est identique à `obj = new Object()`, où`Object`est une fonction constructeur de l'objet intégrée, avec son propre`prototype`référençant un énorme objet avec`toString`et d'autres méthodes.
19
19
20
-
Here's what's going on:
20
+
Voici ce qui se passe:
21
21
22
22

23
23
24
-
When`new Object()`is called (or a literal object`{...}`is created), the`[[Prototype]]`of it is set to`Object.prototype`according to the rule that we discussed in the previous chapter:
24
+
Lorsque`new Object()`est appelé (ou un objet littéral`{...}`est créé), le`[[Prototype]]`de celui-ci est défini sur`Object.prototype`conformément à la règle dont nous avons parlé dans le chapitre précédent:
25
25
26
26

27
27
28
-
So then when `obj.toString()` is called the method is taken from`Object.prototype`.
28
+
Ainsi, quand on appelle `obj.toString()`, la méthode est extraite de`Object.prototype`.
Please note that there is no more`[[Prototype]]`in the chain above`Object.prototype`:
39
+
Veuillez noter qu'il n'y a plus de`[[Prototype]]`dans la chaîne au dessus de`Object.prototype`:
40
40
41
41
```js run
42
42
alert(Object.prototype.__proto__); // null
43
43
```
44
44
45
-
## Other built-in prototypes
45
+
## Autres prototypes intégrés
46
46
47
-
Other built-in objects such as`Array`, `Date`, `Function`and others also keep methods in prototypes.
47
+
D'autres objets intégrés, tels que`Array`, `Date`, `Function`et autres, conservent également des méthodes dans des prototypes.
48
48
49
-
For instance, when we create an array`[1, 2, 3]`, the default`new Array()`constructor is used internally. So`Array.prototype`becomes its prototype and provides methods. That's very memory-efficient.
49
+
Par exemple, lorsque nous créons un tableau`[1, 2, 3]`, le constructeur`new Array()`par défaut est utilisé en interne. Donc`Array.prototype`devient son prototype et fournit des méthodes. C'est très efficace en mémoire.
50
50
51
-
By specification, all of the built-in prototypes have `Object.prototype`on the top. That's why some people say that "everything inherits from objects".
51
+
Par spécification, tous les prototypes intégrés ont `Object.prototype`en haut. C'est pourquoi certaines personnes disent que "tout hérite d'objets".
52
52
53
-
Here's the overall picture (for 3 built-ins to fit):
Some methods in prototypes may overlap, for instance, `Array.prototype`has its own`toString`that lists comma-delimited elements:
72
+
Certaines méthodes dans les prototypes peuvent se chevaucher, par exemple, `Array.prototype`a son propre`toString`qui répertorie les éléments délimités par des virgules:
73
73
74
74
```js run
75
75
let arr = [1, 2, 3]
76
-
alert(arr); // 1,2,3 <-- the result of Array.prototype.toString
76
+
alert(arr); // 1,2,3 <-- le résultat de Array.prototype.toString
77
77
```
78
78
79
-
As we've seen before, `Object.prototype`has `toString` as well, but`Array.prototype`is closer in the chain, so the array variant is used.
79
+
Comme nous l'avons vu précédemment, `Object.prototype`a aussi `toString`, mais`Array.prototype`est plus proche dans la chaîne, la variante de tableau est donc utilisée.
80
80
81
81
82
82

83
83
84
84
85
-
In-browser tools like Chrome developer console also show inheritance (`console.dir`may need to be used for built-in objects):
85
+
Les outils intégrés au navigateur, tels que la console de développement Chrome, affichent également l'héritage (il faut éventuellement utiliser `console.dir`pour les objets intégrés):
86
86
87
87

88
88
89
-
Other built-in objects also work the same way. Even functions -- they are objects of a built-in `Function` constructor, and their methods (`call`/`apply`and others) are taken from`Function.prototype`. Functions have their own `toString` too.
89
+
Les autres objets intégrés fonctionnent également de la même manière. Même les fonctions - ce sont des objets d'un constructeur intégré `Function`, et leurs méthodes (`call`/`apply`et autres) sont extraites de`Function.prototype`. Les fonctions ont aussi leur propre `toString`.
90
90
91
91
```js run
92
92
functionf() {}
93
93
94
94
alert(f.__proto__==Function.prototype); // true
95
-
alert(f.__proto__.__proto__==Object.prototype); // true, inherit from objects
The most intricate thing happens with strings, numbers and booleans.
100
+
Une chose complexe se produit avec les chaînes, les nombres et les booléens.
101
101
102
-
As we remember, they are not objects. But if we try to access their properties, then temporary wrapper objects are created using built-in constructors `String`,`Number`, `Boolean`, they provide the methods and disappear.
102
+
Comme on s'en souvient, ce ne sont pas des objets. Mais si nous essayons d'accéder à leurs propriétés, des objets wrapper temporaires sont créés à l'aide des constructeurs intégrés `String`,`Number`, `Boolean`, ils fournissent les méthodes et disparaissent.
103
103
104
-
These objects are created invisibly to us and most engines optimize them out, but the specification describes it exactly this way. Methods of these objects also reside in prototypes, available as `String.prototype`, `Number.prototype`and`Boolean.prototype`.
104
+
Ces objets sont créés de manière invisible pour nous et la plupart des moteurs les optimisent, mais la spécification le décrit exactement de cette façon. Les méthodes de ces objets résident également dans des prototypes, disponibles sous les noms `String.prototype`, `Number.prototype`et`Boolean.prototype`.
105
105
106
-
```warn header="Values `null`and`undefined`have no object wrappers"
107
-
Special values `null`and`undefined`stand apart. They have no object wrappers, so methods and properties are not available for them. And there are no corresponding prototypes too.
106
+
```warn header="Les valeurs `null`et`undefined`n'ont pas de wrappers d'objet"
107
+
Les valeurs spéciales `null`et`undefined`sont distinctes. Ils n'ont pas de wrapper d'objet, donc les méthodes et les propriétés ne sont pas disponibles pour eux. Et il n'y a pas non plus de prototypes correspondants.
## Modification des prototypes natifs [#native-prototype-change]
111
111
112
-
Native prototypes can be modified. For instance, if we add a method to `String.prototype`, it becomes available to all strings:
112
+
Les prototypes natifs peuvent être modifiés. Par exemple, si nous ajoutons une méthode à `String.prototype`, elle devient disponible pour toutes les chaînes:
During the process of development, we may have ideas for new built-in methods we'd like to have, and we may be tempted to add them to native prototypes. But that is generally a bad idea.
122
+
Au cours du processus de développement, nous pouvons avoir des idées de nouvelles méthodes intégrées que nous aimerions avoir et nous pourrions être tentés de les ajouter à des prototypes natifs. Mais c'est généralement une mauvaise idée.
123
123
124
124
```warn
125
-
Prototypes are global, so it's easy to get a conflict. If two libraries add a method `String.prototype.show`, then one of them will be overwriting the method of the other.
125
+
Les prototypes sont globaux, il est donc facile de créer un conflit. Si deux bibliothèques ajoutent une méthode `String.prototype.show`, l'une d'elles remplacera la méthode de l'autre.
126
126
127
-
So, generally, modifying a native prototype is considered a bad idea.
127
+
Donc, généralement, modifier un prototype natif est considéré comme une mauvaise idée.
128
128
```
129
129
130
-
**In modern programming, there is only one case where modifying native prototypes is approved. That's polyfilling.**
130
+
**Dans la programmation moderne, il n'y a qu'un seul cas où la modification de prototypes natifs est approuvée. Le polyfilling.**
131
131
132
-
Polyfilling is a term for making a substitute for a method that exists in JavaScript specification, but not yet supported by current JavaScript engine.
132
+
Le terme Polyfill décrit l'action de faire un substitut à une méthode qui existe dans la spécification JavaScript, mais pas encore pris en charge par le moteur actuel JavaScript.
133
133
134
-
Then we may implement it manually and populate the built-in prototype with it.
134
+
Ensuite, nous pouvons l’implémenter manuellement et y ajouter le prototype intégré.
135
135
136
-
For instance:
136
+
Par exemple:
137
137
138
138
```js run
139
-
if (!String.prototype.repeat) { //if there's no such method
140
-
//add it to the prototype
139
+
if (!String.prototype.repeat) { //s'il n'y a pas une telle méthode
140
+
//ajouter le au prototype
141
141
142
142
String.prototype.repeat=function(n) {
143
-
//repeat the string n times
143
+
//répéter la chaîne n fois
144
144
145
-
//actually, the code should be a little bit more complex than that
146
-
// (the full algorithm is in the specification)
147
-
//but even an imperfect polyfill is often considered good enough for use
145
+
//en fait, le code devrait être un peu plus complexe que cela
146
+
// (l'algorithme complet est dans la spécification)
147
+
//mais même un polyfill imparfait est souvent considéré comme suffisant pour être utilisé
It works, because the internal algorithm of the built-in `join`method only cares about the correct indexes and the `length` property, it doesn't check that the object is indeed the array. And many built-in methods are like that.
182
+
Cela fonctionne car l'algorithme interne de la méthode `join`intégrée ne se préoccupe que des index corrects et de la propriété `length`, il ne vérifie pas que l'objet est bien un tableau. Et beaucoup de méthodes intégrées sont comme ça.
183
183
184
-
Another possibility is to inherit by setting `obj.__proto__` to`Array.prototype`, so all `Array`methods are automatically available in`obj`.
184
+
Une autre possibilité consiste à hériter en fixant `obj.__ proto__` sur`Array.prototype`, afin que toutes les méthodes `Array`soient automatiquement disponibles dans`obj`.
185
185
186
-
But that's impossible if`obj`already inherits from another object. Remember, we only can inherit from one object at a time.
186
+
Mais c'est impossible si`obj`hérite déjà d'un autre objet. N'oubliez pas que nous ne pouvons hériter que d'un objet à la fois.
187
187
188
-
Borrowing methods is flexible, it allows to mix functionality from different objects if needed.
188
+
L'emprunt des méthodes est flexible, cela permet de mélanger la fonctionnalité des objets différents en cas de besoin.
189
189
190
-
## Summary
190
+
## Résumé
191
191
192
-
-All built-in objects follow the same pattern:
193
-
-The methods are stored in the prototype (`Array.prototype`, `Object.prototype`, `Date.prototype` etc).
194
-
-The object itself stores only the data (array items, object properties, the date).
195
-
-Primitives also store methods in prototypes of wrapper objects: `Number.prototype`, `String.prototype`, `Boolean.prototype`. Only`undefined`and`null`do not have wrapper objects.
196
-
-Built-in prototypes can be modified or populated with new methods. But it's not recommended to change them. Probably the only allowable cause is when we add-in a new standard, but not yet supported by the engine JavaScript method.
192
+
-Tous les objets intégrés suivent le même schéma:
193
+
-Les méthodes sont stockées dans le prototype (`Array.prototype`, `Object.prototype`, `Date.prototype`, etc.).
194
+
-L'objet lui-même ne stocke que les données (éléments de tableau, propriétés de l'objet, date).
195
+
-Les primitives stockent également des méthodes dans des prototypes d'objets wrapper: `Number.prototype`, `String.prototype`, `Boolean.prototype`. Seuls`undefined`et`null`n'ont pas d'objets wrapper.
196
+
-Les prototypes intégrés peuvent être modifiés ou remplis avec de nouvelles méthodes. Mais il n'est pas recommandé de les changer. La seule cause possible est probablement l’ajout d’un nouveau standard, mais pas encore pris en charge par la méthode JavaScript du moteur.
0 commit comments