Skip to content

Commit 887e731

Browse files
authored
Merge pull request #398 from danilolmc/update-pt-instanceof
Class checking: "instanceof"
2 parents 6a52867 + fef2ea7 commit 887e731

File tree

3 files changed

+74
-74
lines changed

3 files changed

+74
-74
lines changed
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
Yeah, looks strange indeed.
1+
Sim, parece estranho de fato.
22

3-
But `instanceof` does not care about the function, but rather about its `prototype`, that it matches against the prototype chain.
3+
Porém, `instanceof` não se importa com a função, mas sim com o seu `prototype`, e assim procura correspondência na cadeia de protótipos.
44

5-
And here `a.__proto__ == B.prototype`, so `instanceof` returns `true`.
5+
E aqui em `a.__proto__ == B.prototype`, `instanceof` retorna `true`.
66

7-
So, by the logic of `instanceof`, the `prototype` actually defines the type, not the constructor function.
7+
Então, pela lógica de `instanceof`, o `prototype` na verdade define o tipo, não é a função construtora.

1-js/09-classes/06-instanceof/1-strange-instanceof/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
importance: 5
1+
Importance: 5
22

33
---
44

5-
# Strange instanceof
5+
# instanceof estranho
66

7-
In the code below, why does `instanceof` return `true`? We can easily see that `a` is not created by `B()`.
7+
No código abaixo, por que `instanceof` retorna `true`? Podemos ver facilmente que `a` não é criado por `B()`.
88

99
```js run
1010
function A() {}
Lines changed: 67 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,62 @@
1-
# Class checking: "instanceof"
1+
# Verificação de classe: "instanceof"
22

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

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

7-
## The instanceof operator [#ref-instanceof]
7+
## O operador instanceof [#ref-instanceof]
88

9-
The syntax is:
9+
A sintaxe é:
1010
```js
1111
obj instanceof Class
1212
```
1313

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

16-
For instance:
16+
Por exemplo:
1717

1818
```js run
1919
class Rabbit {}
2020
let rabbit = new Rabbit();
2121

22-
// is it an object of Rabbit class?
22+
// é um objeto da classe Rabbit?
2323
*!*
2424
alert( rabbit instanceof Rabbit ); // true
2525
*/!*
2626
```
2727

28-
It also works with constructor functions:
28+
Também funciona com funções construtoras:
2929

3030
```js run
3131
*!*
32-
// instead of class
32+
// ao invés de class
3333
function Rabbit() {}
3434
*/!*
3535

3636
alert( new Rabbit() instanceof Rabbit ); // true
3737
```
3838

39-
...And with built-in classes like `Array`:
39+
...E também com classes nativas como `Array`:
4040

4141
```js run
4242
let arr = [1, 2, 3];
4343
alert( arr instanceof Array ); // true
4444
alert( arr instanceof Object ); // true
4545
```
4646

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

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

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

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

55-
For example:
55+
Por exemplo:
5656

5757
```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
6060
class Animal {
6161
static [Symbol.hasInstance](obj) {
6262
if (obj.canEat) return true;
@@ -65,24 +65,24 @@ The algorithm of `obj instanceof Class` works roughly as follows:
6565

6666
let obj = { canEat: true };
6767

68-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
68+
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) é executado
6969
```
7070

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

73-
In other words, compare one after another:
73+
Em outras palavras, compara um após o outro:
7474
```js
7575
obj.__proto__ === Class.prototype?
7676
obj.__proto__.__proto__ === Class.prototype?
7777
obj.__proto__.__proto__.__proto__ === Class.prototype?
7878
...
79-
// if any answer is true, return true
80-
// otherwise, if we reached the end of the chain, return false
79+
// se qualquer reposta for verdadeira, retorna true
80+
// do contrário, se chegarmos ao fim da cedeia, retorna false
8181
```
8282

83-
In the example above `rabbit.__proto__ === Rabbit.prototype`, so that gives the answer immediately.
83+
No exemplo acima `rabbit.__proto__ === Rabbit.prototype`, de modo que dá a resposta imediatamente.
8484

85-
In the case of an inheritance, the match will be at the second step:
85+
No caso de uma herança, a correspondência será na segunda etapa:
8686

8787
```js run
8888
class Animal {}
@@ -93,76 +93,76 @@ The algorithm of `obj instanceof Class` works roughly as follows:
9393
alert(rabbit instanceof Animal); // true
9494
*/!*
9595
96-
// rabbit.__proto__ === Animal.prototype (no match)
96+
// rabbit.__proto__ === Animal.prototype (sem correspondência)
9797
*!*
98-
// rabbit.__proto__.__proto__ === Animal.prototype (match!)
98+
// rabbit.__proto__.__proto__ === Animal.prototype (correspondência!)
9999
*/!*
100100
```
101101

102-
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`
103103

104104
![](instanceof.svg)
105105

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)`.
107107

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

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

112-
Like here:
112+
Como nesse exemplo:
113113

114114
```js run
115115
function Rabbit() {}
116116
let rabbit = new Rabbit();
117117
118-
// changed the prototype
118+
// alterou o prototype
119119
Rabbit.prototype = {};
120120
121-
// ...not a rabbit any more!
121+
// ...não é mais um coelho!
122122
*!*
123123
alert( rabbit instanceof Rabbit ); // false
124124
*/!*
125125
```
126126

127-
## Bonus: Object.prototype.toString for the type
127+
## Bonus: Object.prototype.toString para o tipo
128128

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]`:
130130

131131
```js run
132132
let obj = {};
133133
134134
alert(obj); // [object Object]
135-
alert(obj.toString()); // the same
135+
alert(obj.toString()); // o mesmo
136136
```
137137

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`
139139

140-
Sounds strange? Indeed. Let's demystify.
140+
Soa estranho? De fato. Vamos desmistificar.
141141

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

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).
150150

151-
Let's demonstrate:
151+
Vamos demonstrar:
152152

153153
```js run
154-
// copy toString method into a variable for convenience
154+
// copia o método toString para uma variável por conveniência
155155
let objectToString = Object.prototype.toString;
156156
157-
// what type is this?
157+
// Que tipo é esse?
158158
let arr = [];
159159
160160
alert( objectToString.call(arr) ); // [object *!*Array*/!*]
161161
```
162162

163-
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`.
164164

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

167167
```js run
168168
let s = Object.prototype.toString;
@@ -174,9 +174,9 @@ alert( s.call(alert) ); // [object Function]
174174

175175
### Symbol.toStringTag
176176

177-
The behavior of Object `toString` can be customized using a special object property `Symbol.toStringTag`.
177+
O comportamento de Object `toString` pode ser personalizado usando uma propriedade de objeto especial `Symbol.toStringTag`.
178178

179-
For instance:
179+
Por exemplo:
180180

181181
```js run
182182
let user = {
@@ -186,33 +186,33 @@ let user = {
186186
alert( {}.toString.call(user) ); // [object User]
187187
```
188188

189-
For most environment-specific objects, there is such a property. Here are some browser specific examples:
189+
Para a maioria dos objetos nativos aos diversos ambientes, existe essa propriedade. Aqui estão alguns exemplos específicos do navegador:
190190

191191
```js run
192-
// toStringTag for the environment-specific object and class:
192+
// toStringTag para o objeto e a classe nativos ao ambiente:
193193
alert( window[Symbol.toStringTag]); // Window
194194
alert( XMLHttpRequest.prototype[Symbol.toStringTag] ); // XMLHttpRequest
195195
196196
alert( {}.toString.call(window) ); // [object Window]
197197
alert( {}.toString.call(new XMLHttpRequest()) ); // [object XMLHttpRequest]
198198
```
199199

200-
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 ...]`.
201201

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

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

206-
## Summary
206+
## Conclusão
207207

208-
Let's summarize the type-checking methods that we know:
208+
Vamos listar os métodos de checagem de tipos que conhecemos:
209209

210-
| | works for | returns |
211-
|---------------|-------------|---------------|
212-
| `typeof` | primitives | string |
213-
| `{}.toString` | primitives, built-in objects, objects with `Symbol.toStringTag` | string |
214-
| `instanceof` | objects | true/false |
210+
| | funciona para | retorna |
211+
|---------------|-----------------|---------------|
212+
| `typeof` | primitivos | string |
213+
| `{}.toString` | primitivos, objetos nativos, objetos com `Symbol.toStringTag` | string |
214+
| `instanceof` | objetos | true/false |
215215

216-
As we can see, `{}.toString` is technically a "more advanced" `typeof`.
216+
Como podemos ver, `{}.toString` é tecnicamente um `typeof` "mais avançado".
217217

218-
And `instanceof` operator really shines when we are working with a class hierarchy and want to check for the class taking 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

Comments
 (0)