Skip to content

Commit 9feaffd

Browse files
authored
Merge pull request #68 from TevaHenry/master
Native prototypes
2 parents cbce59f + 93fc879 commit 9feaffd

File tree

5 files changed

+73
-73
lines changed

5 files changed

+73
-73
lines changed

1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ function f() {
99
alert("Hello!");
1010
}
1111

12-
f.defer(1000); // shows "Hello!" after 1 sec
12+
f.defer(1000); // montre "Hello!" après 1 seconde
1313
```

1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ importance: 5
22

33
---
44

5-
# Add method "f.defer(ms)" to functions
5+
# Ajouter la méthode "f.defer(ms)" aux fonctions
66

7-
Add to the prototype of all functions the method `defer(ms)`, that runs the function after `ms` milliseconds.
7+
Ajoutez au prototype de toutes les fonctions la méthode `defer(ms)`, qui exécute la fonction après `ms` millisecondes.
88

9-
After you do it, such code should work:
9+
Une fois que vous le faites, ce code devrait fonctionner:
1010

1111
```js
1212
function f() {
1313
alert("Hello!");
1414
}
1515

16-
f.defer(1000); // shows "Hello!" after 1 second
16+
f.defer(1000); // montre "Hello!" après 1 seconde
1717
```

1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ Function.prototype.defer = function(ms) {
88
}
99
};
1010

11-
// check it
11+
// vérifier
1212
function f(a, b) {
1313
alert( a + b );
1414
}
1515

16-
f.defer(1000)(1, 2); // shows 3 after 1 sec
16+
f.defer(1000)(1, 2); // montre 3 après 1 seconde
1717
```

1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ importance: 4
22

33
---
44

5-
# Add the decorating "defer()" to functions
5+
# Ajouter la décoration "defer()" aux fonctions
66

7-
Add to the prototype of all functions the method `defer(ms)`, that returns a wrapper, delaying the call by `ms` milliseconds.
7+
Ajoutez au prototype de toutes les fonctions la méthode `defer(ms)`, qui renvoie un wrapper, retardant l’appel de `ms` millisecondes.
88

9-
Here's an example of how it should work:
9+
Voici un exemple de la façon dont cela devrait fonctionner:
1010

1111
```js
1212
function f(a, b) {
1313
alert( a + b );
1414
}
1515

16-
f.defer(1000)(1, 2); // shows 3 after 1 second
16+
f.defer(1000)(1, 2); // montre 3 après 1 seconde
1717
```
1818

19-
Please note that the arguments should be passed to the original function.
19+
Veuillez noter que les arguments doivent être passés à la fonction d'origine.
Lines changed: 61 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1-
# Native prototypes
1+
# Prototypes natifs
22

3-
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.
44

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.
66

77
## Object.prototype
88

9-
Let's say we output an empty object:
9+
Disons que nous produisons un objet vide:
1010

1111
```js run
1212
let obj = {};
1313
alert( obj ); // "[object Object]" ?
1414
```
1515

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!
1717

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()`, `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.
1919

20-
Here's what's going on:
20+
Voici ce qui se passe:
2121

2222
![](object-prototype.svg)
2323

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:
2525

2626
![](object-prototype-1.svg)
2727

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`.
2929

30-
We can check it like this:
30+
Nous pouvons le vérifier comme ceci:
3131

3232
```js run
3333
let obj = {};
@@ -36,80 +36,80 @@ alert(obj.__proto__ === Object.prototype); // true
3636
// obj.toString === obj.__proto__.toString == Object.prototype.toString
3737
```
3838

39-
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`:
4040

4141
```js run
4242
alert(Object.prototype.__proto__); // null
4343
```
4444

45-
## Other built-in prototypes
45+
## Autres prototypes intégrés
4646

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.
4848

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.
5050

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".
5252

53-
Here's the overall picture (for 3 built-ins to fit):
53+
Voici la vue d'ensemble:
5454

5555
![](native-prototypes-classes.svg)
5656

57-
Let's check the prototypes manually:
57+
Vérifions les prototypes manuellement:
5858

5959
```js run
6060
let arr = [1, 2, 3];
6161

62-
// it inherits from Array.prototype?
62+
// il hérite de Array.prototype?
6363
alert( arr.__proto__ === Array.prototype ); // true
6464

65-
// then from Object.prototype?
65+
// puis de Object.prototype?
6666
alert( arr.__proto__.__proto__ === Object.prototype ); // true
6767

68-
// and null on the top.
68+
// et null tout en haut.
6969
alert( arr.__proto__.__proto__.__proto__ ); // null
7070
```
7171

72-
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:
7373

7474
```js run
7575
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
7777
```
7878

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.
8080

8181

8282
![](native-prototypes-array-tostring.svg)
8383

8484

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):
8686

8787
![](console_dir_array.png)
8888

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`.
9090

9191
```js run
9292
function f() {}
9393

9494
alert(f.__proto__ == Function.prototype); // true
95-
alert(f.__proto__.__proto__ == Object.prototype); // true, inherit from objects
95+
alert(f.__proto__.__proto__ == Object.prototype); // true, hérite d'objets
9696
```
9797

9898
## Primitives
9999

100-
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.
101101

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.
103103

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`.
105105

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.
108108
```
109109
110-
## Changing native prototypes [#native-prototype-change]
110+
## Modification des prototypes natifs [#native-prototype-change]
111111
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:
113113
114114
```js run
115115
String.prototype.show = function() {
@@ -119,32 +119,32 @@ String.prototype.show = function() {
119119
"BOOM!".show(); // BOOM!
120120
```
121121

122-
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.
123123

124124
```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.
126126
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.
128128
```
129129

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.**
131131

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.
133133

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é.
135135

136-
For instance:
136+
Par exemple:
137137

138138
```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
141141

142142
String.prototype.repeat = function(n) {
143-
// repeat the string n times
143+
// répéter la chaîne n fois
144144

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é
148148
return new Array(n + 1).join(this);
149149
};
150150
}
@@ -153,15 +153,15 @@ alert( "La".repeat(3) ); // LaLaLa
153153
```
154154

155155

156-
## Borrowing from prototypes
156+
## Emprunt de prototypes
157157

158-
In the chapter <info:call-apply-decorators#method-borrowing> we talked about method borrowing.
158+
Dans le chapitre <info:call-apply-decorators#method-borrowing> nous avons parlé de l'emprunt de méthode.
159159

160-
That's when we take a method from one object and copy it into another.
160+
C'est quand nous prenons une méthode d'un objet et le copions dans un autre.
161161

162-
Some methods of native prototypes are often borrowed.
162+
Certaines méthodes de prototypes natifs sont souvent empruntés.
163163

164-
For instance, if we're making an array-like object, we may want to copy some `Array` methods to it.
164+
Par exemple, si nous créons un objet semblable à un tableau, nous voudrons peut-être y copier des méthodes `Array`.
165165

166166
E.g.
167167

@@ -179,18 +179,18 @@ obj.join = Array.prototype.join;
179179
alert( obj.join(',') ); // Hello,world!
180180
```
181181

182-
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.
183183

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`.
185185

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.
187187

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.
189189

190-
## Summary
190+
## Résumé
191191

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

Comments
 (0)