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`instanceof`operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
3
+
L'opérateur`instanceof`permet de vérifier si un objet appartient à une certaine classe. Il prend également en compte l'héritage.
4
4
5
-
Such a check may be necessary in many cases, here we'll use it for building a *polymorphic* function, the one that treats arguments differently depending on their type.
5
+
Une telle vérification peut être nécessaire dans de nombreux cas. Nous l'utilisons ici pour construire une fonction *polymorphique*, celle qui traite les arguments différemment en fonction de leur type.
6
6
7
-
## The instanceof operator[#ref-instanceof]
7
+
## L'opérateur instanceof [#ref-instanceof]
8
8
9
-
The syntax is:
9
+
La syntaxe est la suivante:
10
10
```js
11
11
obj instanceof Class
12
12
```
13
13
14
-
It returns`true`if`obj`belongs to the`Class`or a class inheriting from it.
14
+
Cela renvoie`true`si`obj`appartient à la`Class`ou à une classe qui en hérite.
15
15
16
-
For instance:
16
+
Par exemple:
17
17
18
18
```js run
19
19
classRabbit {}
20
20
let rabbit =newRabbit();
21
21
22
-
//is it an object of Rabbit class?
22
+
//est-ce un objet de la classe Rabbit?
23
23
*!*
24
24
alert( rabbit instanceof Rabbit ); // true
25
25
*/!*
26
26
```
27
27
28
-
It also works with constructor functions:
28
+
Cela fonctionne aussi avec les fonctions constructeur:
29
29
30
30
```js run
31
31
*!*
32
-
//instead of class
32
+
//au lieu de classe
33
33
functionRabbit() {}
34
34
*/!*
35
35
36
36
alert( newRabbit() instanceof Rabbit ); // true
37
37
```
38
38
39
-
...And with built-in classes like`Array`:
39
+
...Et avec des classes intégrées comme`Array`:
40
40
41
41
```js run
42
42
let arr = [1, 2, 3];
43
43
alert( arr instanceofArray ); // true
44
44
alert( arr instanceofObject ); // true
45
45
```
46
46
47
-
Please note that`arr`also belongs to the `Object` class. That's because `Array`prototypally inherits from`Object`.
47
+
Veuillez noter que`arr`appartient également à la classe `Object`. C'est parce que `Array`hérite prototypiquement de`Object`.
48
48
49
-
Normally, `instanceof`operator examines the prototype chain for the check. We can also set a custom logic in the static method`Symbol.hasInstance`.
49
+
Normalement, l’opérateur `instanceof`examine la chaîne de prototypes pour le contrôle. Nous pouvons également définir une logique personnalisée dans la méthode statique`Symbol.hasInstance`.
50
50
51
-
The algorithm of `obj instanceof Class`works roughly as follows:
51
+
L'algorithme de `obj instanceof Class`fonctionne à peu près comme suit:
52
52
53
-
1.If there's a static method `Symbol.hasInstance`, then just call it: `Class[Symbol.hasInstance](obj)`. It should return either `true`or`false`, and we're done. That's how we can customize the behavior of`instanceof`.
53
+
1.S'il existe une méthode statique `Symbol.hasInstance`, appelez-la simplement: `Class[Symbol.hasInstance](obj)`. Cela devrait renvoyer `true`ou`false`, et nous avons terminé. C'est ainsi que nous pouvons personnaliser le comportement de`instanceof`.
54
54
55
-
For example:
55
+
Par exemple:
56
56
57
-
```js run
58
-
// setup instanceOf check that assumes that
59
-
// anything with canEat property is an animal
60
-
classAnimal {
61
-
static [Symbol.hasInstance](obj) {
62
-
if (obj.canEat) returntrue;
63
-
}
64
-
}
57
+
```js run
58
+
// configuration du contrôle de instanceOf qui suppose que
59
+
// tout ce qui a la propriété canEat est un animal
60
+
classAnimal {
61
+
static [Symbol.hasInstance](obj) {
62
+
if (obj.canEat) returntrue;
63
+
}
64
+
}
65
65
66
-
let obj = { canEat:true };
66
+
let obj = { canEat:true };
67
67
68
-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
69
-
```
68
+
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) est appelée
69
+
```
70
70
71
-
2.Most classes do not have `Symbol.hasInstance`. In that case, the standard logic is used:`obj instanceOf Class`checks whether`Class.prototype`equals to one ofprototypes in the `obj` prototype chain.
71
+
2.La plupart des classes n'ont pas `Symbol.hasInstance`. Dans ce cas, la logique standard est utilisée: `obj instanceOf Class`vérifie si`Class.prototype`est égal à l'un des prototypes de la chaîne de prototypes `obj`.
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
102
+
Voici l'illustration de ce que `rabbit instanceof Animal`compare avec`Animal.prototype`:
103
103
104
104

105
105
106
-
By the way, there's also a method [objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf), that returns`true`if`objA`is somewhere in the chain ofprototypes for`objB`. So the test of`obj instanceof Class`can be rephrased as `Class.prototype.isPrototypeOf(obj)`.
106
+
À propos, il y a aussi une méthode [objA.isPrototypeOf(objB)](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/isPrototypeOf), qui renvoie`true`si`objA`se trouve quelque part dans la chaîne de prototypes pour`objB`. Ainsi, le test de`obj instanceof Class`peut être reformulé comme suit: `Class.prototype.isPrototypeOf(obj)`.
107
107
108
-
That's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
108
+
C'est drôle, mais le constructeur `Class`lui-même ne participe pas au contrôle! Seule la chaîne de prototypes et`Class.prototype`compte.
109
109
110
-
That can lead to interesting consequences when `prototype` property is changed after the object is created.
110
+
Cela peut avoir des conséquences intéressantes lorsque la propriété `prototype`est modifiée après la création de l'objet.
111
111
112
-
Like here:
112
+
Comme ici:
113
113
114
114
```js run
115
115
functionRabbit() {}
116
116
let rabbit =newRabbit();
117
117
118
-
// changed the prototype
118
+
//le prototype est changé
119
119
Rabbit.prototype= {};
120
120
121
-
// ...not a rabbit any more!
121
+
// ...plus un rabbit!
122
122
*!*
123
123
alert( rabbit instanceof Rabbit ); // false
124
124
*/!*
125
125
```
126
126
127
-
## Bonus: Object.prototype.toString for the type
127
+
## Bonus: Object.prototype.toString pour le type
128
128
129
-
We already know that plain objects are converted to string as `[object Object]`:
129
+
Nous savons déjà que les objets simples sont convertis en chaîne sous la forme `[objet Objet]`:
130
130
131
131
```js run
132
132
let obj = {};
133
133
134
134
alert(obj); // [object Object]
135
-
alert(obj.toString()); // the same
135
+
alert(obj.toString()); //la même chose
136
136
```
137
137
138
-
That's their implementation of`toString`. But there's a hidden feature that makes `toString` actually much more powerful than that. We can use it as an extended `typeof` and an alternative for `instanceof`.
138
+
C'est leur implémentation de`toString`. Mais il existe une fonctionnalité cachée qui rend `toString`beaucoup plus puissant que cela. Nous pouvons l'utiliser comme un `typeof`étendu et une alternative pour`instanceof`.
139
139
140
-
Sounds strange? Indeed. Let's demystify.
140
+
Cela semble étrange? Effectivement. Démystifions.
141
141
142
-
By [specification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), the built-in `toString` can be extracted from the object and executed in the context of any other value. And its result depends on that value.
142
+
Par [spécification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), le `toString`intégré peut être extrait de l'objet et exécuté dans le contexte de toute autre valeur. Et son résultat dépend de cette valeur.
143
143
144
-
-For a number, it will be`[object Number]`
145
-
-For a boolean, it will be`[object Boolean]`
146
-
-For`null`:`[object Null]`
147
-
-For`undefined`:`[object Undefined]`
148
-
-For arrays:`[object Array]`
149
-
-...etc (customizable).
144
+
- Pour un nombre, ce sera`[object Number]`
145
+
- Pour un booléen, ce sera`[object Boolean]`
146
+
- Pour`null`: `[objet Null]`
147
+
- Pour`undefined`: `[objet Undefined]`
148
+
- Pour les tableaux: `[objetArray]`
149
+
- ...etc (personnalisable).
150
150
151
-
Let's demonstrate:
151
+
Montrons cela:
152
152
153
153
```js run
154
-
// copy toString method into a variable for convenience
154
+
//copier la méthode toString dans une variable pour plus d'utilité
Here we used [call](mdn:js/function/call) as described in the chapter [](info:call-apply-decorators) to execute the function `objectToString` in the context `this=arr`.
163
+
Ici nous avons utilisé [call](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Function/call) comme décrit dans le chapitre [](info:call-apply-decorators) exécuter la fonction `objectToString`dans le contexte`this=arr`.
164
164
165
-
Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
165
+
En interne, l'algorithme`toString`examine `this`et renvoie le résultat correspondant. Plus d'exemples:
As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped into `[object ...]`.
200
+
Comme vous pouvez le constater, le résultat est exactement`Symbol.toStringTag` (s'il existe), encapsulé dans`[objet...]`.
201
201
202
-
At the end we have "typeof on steroids" that not only works for primitive data types, but also for built-in objects and even can be customized.
202
+
À la fin, nous avons "typeof sur stéroïdes" qui fonctionne non seulement pour les types de données primitifs, mais aussi pour les objets intégrés et peut même être personnalisé.
203
203
204
-
We can use `{}.toString.call` instead of `instanceof` for built-in objects when we want to get the type as a string rather than just to check.
204
+
Nous pouvons utiliser`{}.toString.call`au lieu de `instanceof`pour les objets intégrés lorsque nous voulons obtenir le type sous forme de chaîne plutôt que simplement pour vérifier.
205
205
206
-
## Summary
206
+
## Résumé
207
207
208
-
Let's summarize the type-checking methods that we know:
208
+
Résumons les méthodes de vérification de type que nous connaissons:
As we can see, `{}.toString`is technically a "more advanced"`typeof`.
216
+
Comme on peut le constater, `{}.toString`est techniquement un `typeof` "plus avancé".
217
217
218
-
And `instanceof`operator really shines when we are working with a classhierarchy and want to check for the classtaking into account inheritance.
218
+
Et l'opérateur `instanceof`excelle lorsque nous travaillons avec une hiérarchie de classes et voulons vérifier si la classe prend en compte l'héritage.
0 commit comments