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
+
O operador `instanceof`permite checar se um objeto pertence a uma determinada classe. Também leva a herança em consideração.
4
4
5
-
Such a check may be necessary in many cases. For example, it can be used for building a *polymorphic* function, the one that treats arguments differently depending on their type.
5
+
Essa verificação pode ser necessária em diversos casos. Por exemplo, pode ser usada para construir uma função *polimórfica*, aquela que lida com argumentos de forma diferente dependendo do seu tipo.
6
6
7
-
## The instanceof operator[#ref-instanceof]
7
+
## O operador instanceof[#ref-instanceof]
8
8
9
-
The syntax is:
9
+
A sintaxe é:
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
+
O código retorna `true`se`obj`pertence à `Class`ou a uma classe herdada dela.
15
15
16
-
For instance:
16
+
Por exemplo:
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
+
//é um objeto da 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
+
Também funciona com funções construtoras:
29
29
30
30
```js run
31
31
*!*
32
-
//instead of class
32
+
//ao invés de class
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
+
...E também com classes nativas como`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`prototypically inherits from`Object`.
47
+
Perceba que `arr`também pertence à classe`Object`. Isso porque`Array`de forma prototípica herda de`Object`.
48
48
49
-
Normally,`instanceof`examines the prototype chain for the check. We can also set a custom logic in the static method `Symbol.hasInstance`.
49
+
Normalmente`instanceof`examina a cadeia de protótipos para a verificação. Também podemos definir uma lógica customizada no método estático `Symbol.hasInstance`.
50
50
51
-
The algorithm of`obj instanceof Class`works roughly as follows:
51
+
O algoritmo de`obj instanceof Class`funciona mais ou menos da seguinte forma:
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.Se houver um método estático`Symbol.hasInstance`, basta executá-lo como: `Class[Symbol.hasInstance](obj)`. Ele deve retornar `true`ou`false`, e é tudo. É assim que podemos customizar o comportamento de`instanceof`.
54
54
55
-
For example:
55
+
Por exemplo:
56
56
57
57
```js run
58
-
//setup instanceOf check that assumes that
59
-
//anything with canEat property is an animal
58
+
//configura a verificação de instanceOf para assumir que
59
+
//qualquer coisa com a propriedade canEat é um animal
60
60
classAnimal {
61
61
static [Symbol.hasInstance](obj) {
62
62
if (obj.canEat) returntrue;
@@ -65,24 +65,24 @@ The algorithm of `obj instanceof Class` works roughly as follows:
65
65
66
66
let obj = { canEat:true };
67
67
68
-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
68
+
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) é executado
69
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`is equal to one of the prototypes in the `obj` prototype chain.
71
+
2.A maioria das classes não possui `Symbol.hasInstance`. Nesse caso, a lógica padrão é usada:`obj instanceOf Class`verfica se `Class.prototype`é igual a um dos protótipos na cadeia de protótipos de `obj`.
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
102
+
Aqui está a ilustração do que `rabbit instanceof Animal`vai comparar com `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 of prototypes for`objB`. So the test of`obj instanceof Class`can be rephrased as`Class.prototype.isPrototypeOf(obj)`.
106
+
A propósito, também existe um método [objA.isPrototypeOf(objB)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf), que retorna `true` se `objA` está em algum lugar na cadeia de protótipos do `objB`. Então o teste de `obj instanceof Class` pode ser reescrito como `Class.prototype.isPrototypeOf(obj)`.
107
107
108
-
It's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
108
+
É engraçado, mas o próprio construtor `Class`não participa na verificação! Apenas a cadeia de protótipos e`Class.prototype`importam.
109
109
110
-
That can lead to interesting consequences when a `prototype` property is changed after the object is created.
110
+
Isso pode levar a consequências interessantes quando uma propriedade `prototype`é alterada depois que um objeto é criado.
111
111
112
-
Like here:
112
+
Como nesse exemplo:
113
113
114
114
```js run
115
115
function Rabbit() {}
116
116
let rabbit = new Rabbit();
117
117
118
-
// changed the prototype
118
+
// alterou o prototype
119
119
Rabbit.prototype = {};
120
120
121
-
// ...not a rabbit any more!
121
+
// ...não é mais um coelho!
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.toStringpara o tipo
128
128
129
-
We already know that plain objects are converted to string as `[object Object]`:
129
+
Já sabemos que objetos simples convertidos para string exibem o texto`[object Object]`:
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()); // o mesmo
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
+
Essa é a implementação deles de `toString`. Porém, há uma característica escondida que torna`toString`realmente muito mais poderoso do que isso. Podemos usá-lo como um `typeof`estendido e uma alternativa para `instanceof`
139
139
140
-
Sounds strange? Indeed. Let's demystify.
140
+
Soa estranho? De fato. Vamos desmistificar.
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
+
Pela [especificação](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), o `toString` nativo pode ser extraído do objeto e executado no contexto de qualquer outro valor. E o seu resultado depende desse valor.
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
+
-Para um número, será`[object Number]`
145
+
-Para boleano, será`[object Boolean]`
146
+
-Para`null`:`[object Null]`
147
+
-Para`undefined`:`[object Undefined]`
148
+
-Para arrays:`[object Array]`
149
+
-...etc (customizável).
150
150
151
-
Let's demonstrate:
151
+
Vamos demonstrar:
152
152
153
153
```js run
154
-
// copy toString method into a variable for convenience
154
+
// copia o método toString para uma variável por conveniência
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
+
Aqui usamos [call](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/call) como descrito no capítulo [](info:call-apply-decorators) para executar a função `objectToString` no contexto `this=arr`.
164
164
165
-
Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
165
+
Internamente, o algoritmo `toString`examina `this`e retorna o resultado correspondente. Mais exemplos:
As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped into `[object ...]`.
200
+
Como pode ver, o resultado é exatamente`Symbol.toStringTag` (Se existir), dentro de`[object ...]`.
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
+
No final, temos "typeof com esteróides" que não funciona apenas para dados primitivos, mas também para objetos nativos e pode até mesmo ser personalizado.
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
+
Podemos usar `{}.toString.call`ao invés de `instanceof`para objetos nativos quando queremos obter o tipo como uma string em vez de apenas verificar.
205
205
206
-
## Summary
206
+
## Conclusão
207
207
208
-
Let's summarize the type-checking methods that we know:
208
+
Vamos listar os métodos de checagem de tipos que conhecemos:
As we can see, `{}.toString`is technically a "more advanced"`typeof`.
216
+
Como podemos ver, `{}.toString`é tecnicamente um `typeof`"mais avançado".
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
+
E o operador `instanceof`realmente brilha quando estamos trabalhando com uma hierarquia de classe e queremos verificar a classe considerando a herança.
0 commit comments