Skip to content

Commit b35438e

Browse files
committed
1-09-06 Traducido 5
1 parent b91261d commit b35438e

4 files changed

Lines changed: 89 additions & 132 deletions

File tree

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
Yeah, looks strange indeed.
1+
Sí, se ve extraño de hecho.
22

3-
But `instanceof` does not care about the function, but rather about its `prototype`, that it matches against the prototype chain.
3+
Pero a `instanceof` no le importa la función, sino más bien su `prototype`, que coincide con la cadena del prototipo.
44

5-
And here `a.__proto__ == B.prototype`, so `instanceof` returns `true`.
5+
Y aquí `a.__ proto__ == B.prototype`, entonces `instanceof` devuelve `true`.
66

7-
So, by the logic of `instanceof`, the `prototype` actually defines the type, not the constructor function.
7+
Entonces, según la lógica de `instanceof`, el `prototype` en realidad define el tipo, no la función constructora.

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
@@ -2,9 +2,9 @@ importance: 5
22

33
---
44

5-
# Strange instanceof
5+
# Extraño instanceof
66

7-
Why `instanceof` below returns `true`? We can easily see that `a` is not created by `B()`.
7+
En el siguiente código, ¿por qué `instanceof` devuelve `true`? Podemos ver fácilmente que `a` no es creado por `B()`.
88

99
```js run
1010
function A() {}
@@ -15,6 +15,6 @@ A.prototype = B.prototype = {};
1515
let a = new A();
1616

1717
*!*
18-
alert( a instanceof B ); // true
18+
alert( a instanceof B ); // verdadero
1919
*/!*
2020
```
Lines changed: 81 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,168 @@
1-
# Class checking: "instanceof"
1+
# Comprobación de clase: "instanceof"
22

3-
The `instanceof` operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
3+
El operador `instanceof` permite verificar si un objeto pertenece a una clase determinada. También tiene en cuenta la herencia.
44

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+
Tal verificación puede ser necesaria en muchos casos. Aquí lo usaremos para construir una función *polimórfica*, la que trata los argumentos de manera diferente dependiendo de su tipo.
66

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

9-
The syntax is:
9+
La sintaxis es:
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+
Devuelve `true` si `obj` pertenece a la `Class` o una clase que hereda de ella.
1515

16-
For instance:
16+
Por ejemplo:
1717

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

22-
// is it an object of Rabbit class?
22+
// ¿Es un objeto de la clase Rabbit?
2323
*!*
24-
alert( rabbit instanceof Rabbit ); // true
24+
alert( rabbit instanceof Rabbit ); // verdadero
2525
*/!*
2626
```
2727

28-
It also works with constructor functions:
28+
También funciona con funciones de constructor:
2929

3030
```js run
3131
*!*
32-
// instead of class
32+
// en lugar de clase
3333
function Rabbit() {}
3434
*/!*
3535

36-
alert( new Rabbit() instanceof Rabbit ); // true
36+
alert( new Rabbit() instanceof Rabbit ); // verdadero
3737
```
3838

39-
...And with built-in classes like `Array`:
39+
...Y con clases integradas como `Array`:
4040

4141
```js run
4242
let arr = [1, 2, 3];
43-
alert( arr instanceof Array ); // true
44-
alert( arr instanceof Object ); // true
43+
alert( arr instanceof Array ); // verdadero
44+
alert( arr instanceof Object ); // verdadero
4545
```
4646

47-
Please note that `arr` also belongs to the `Object` class. That's because `Array` prototypally inherits from `Object`.
47+
Tenga en cuenta que `arr` también pertenece a la clase `Object`. Esto se debe a que `Array` hereda prototípicamente de `Object`.
4848

49-
The `instanceof` operator examines the prototype chain for the check, and is also fine-tunable using the static method `Symbol.hasInstance`.
49+
Normalmente, `instanceof` examina la cadena de prototipos para la verificación. También podemos establecer una lógica personalizada en el método estático `Symbol.hasInstance`.
5050

51-
The algorithm of `obj instanceof Class` works roughly as follows:
51+
El algoritmo de `obj instanceof Class` funciona más o menos de la siguiente manera:
5252

53-
1. If there's a static method `Symbol.hasInstance`, then use it. Like this:
53+
1. Si hay un método estático `Symbol.hasInstance`, simplemente llámelo: `Class[Symbol.hasInstance](obj)`. Debería devolver `true` o `false`, y hemos terminado. Así es como podemos personalizar el comportamiento de `instanceof`.
54+
55+
Por ejemplo:
5456

5557
```js run
56-
// assume anything that canEat is an animal
58+
// Instalar instancia de verificación que asume que
59+
// cualquier cosa con propiedad canEat es un animal
5760
class Animal {
5861
static [Symbol.hasInstance](obj) {
5962
if (obj.canEat) return true;
6063
}
6164
}
6265

6366
let obj = { canEat: true };
64-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
67+
68+
alert(obj instanceof Animal); // verdadero: Animal[Symbol.hasInstance](obj) es llamadoda
6569
```
6670

67-
2. Most classes do not have `Symbol.hasInstance`. In that case, check if `Class.prototype` equals to one of prototypes in the `obj` prototype chain.
71+
2. La mayoría de las clases no tienen `Symbol.hasInstance`. En ese caso, se utiliza la lógica estándar: `obj instanceOf Class` comprueba si `Class.prototype` es igual a uno de los prototipos en la cadena de prototipos `obj`.
6872

69-
In other words, compare:
73+
En otras palabras, compara uno tras otro:
7074
```js
71-
obj.__proto__ === Class.prototype
72-
obj.__proto__.__proto__ === Class.prototype
73-
obj.__proto__.__proto__.__proto__ === Class.prototype
75+
obj.__proto__ === Class.prototype?
76+
obj.__proto__.__proto__ === Class.prototype?
77+
obj.__proto__.__proto__.__proto__ === Class.prototype?
7478
...
79+
// si alguna respuesta es verdadera, devuelve true
80+
// de lo contrario, si llegamos al final de la cadena, devuelve false
7581
```
7682

77-
In the example above `Rabbit.prototype === rabbit.__proto__`, so that gives the answer immediately.
83+
En el ejemplo anterior `rabbit.__ proto__ === Rabbit.prototype`, por lo que da la respuesta de inmediato.
7884

79-
In the case of an inheritance, `rabbit` is an instance of the parent class as well:
85+
En el caso de una herencia, la coincidencia será en el segundo paso:
8086

8187
```js run
8288
class Animal {}
8389
class Rabbit extends Animal {}
8490
8591
let rabbit = new Rabbit();
8692
*!*
87-
alert(rabbit instanceof Animal); // true
93+
alert(rabbit instanceof Animal); // verdadero
8894
*/!*
95+
8996
// rabbit.__proto__ === Rabbit.prototype
90-
// rabbit.__proto__.__proto__ === Animal.prototype (match!)
97+
*!*
98+
// rabbit.__proto__.__proto__ === Animal.prototype (iguala!)
99+
*/!*
91100
```
92101

93-
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
102+
Aquí está la ilustración de lo que `rabbit instanceof Animal` compara con `Animal.prototype`:
94103

95104
![](instanceof.svg)
96105

97-
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+
Por cierto, también hay un método [objA.isPrototypeOf(objB)] (mdn:js/object/isPrototypeOf), que devuelve `true` si `objA` está en algún lugar de la cadena de prototipos para `objB`. Por lo tanto, la prueba de `obj instanceof Class` se puede reformular como `Class.prototype.isPrototypeOf(obj)`.
98107

99-
That's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
108+
Es divertido, ¡pero el constructor `Class` en sí mismo no participa en el chequeo! Solo importa la cadena de prototipos y `Class.prototype`.
100109

101-
That can lead to interesting consequences when `prototype` is changed.
110+
Eso puede llevar a consecuencias interesantes cuando se cambia una propiedad `prototype` después de crear el objeto.
102111

103-
Like here:
112+
Como aquí:
104113

105114
```js run
106115
function Rabbit() {}
107116
let rabbit = new Rabbit();
108117

109-
// changed the prototype
118+
// cambió el prototipo
110119
Rabbit.prototype = {};
111120

112-
// ...not a rabbit any more!
121+
// ...ya no es un conejo!
113122
*!*
114-
alert( rabbit instanceof Rabbit ); // false
123+
alert( rabbit instanceof Rabbit ); // falso
115124
*/!*
116125
```
117126

118-
That's one of the reasons to avoid changing `prototype`. Just to keep safe.
119-
120-
## Bonus: Object toString for the type
127+
## Bonificación: Object.prototype.toString para el tipo
121128

122-
We already know that plain objects are converted to string as `[object Object]`:
129+
Ya sabemos que los objetos simples se convierten en cadenas como `[objetc Objetc]`:
123130

124131
```js run
125132
let obj = {};
126133

127134
alert(obj); // [object Object]
128-
alert(obj.toString()); // the same
135+
alert(obj.toString()); // lo mismo
129136
```
130137

131-
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+
Esa es su implementación de `toString`. Pero hay una característica oculta que hace que `toString` sea mucho más poderoso que eso. Podemos usarlo como un `typeof` extendido y una alternativa para `instanceof`.
132139

133-
Sounds strange? Indeed. Let's demystify.
140+
¿Suena extraño? En efecto. Vamos a desmitificar.
134141

135-
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+
Mediante [especificación](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), el `toString` incorporado puede extraerse del objeto y ejecutarse en el contexto de cualquier otro valor. Y su resultado depende de ese valor.
136143

137-
- For a number, it will be `[object Number]`
138-
- For a boolean, it will be `[object Boolean]`
139-
- For `null`: `[object Null]`
140-
- For `undefined`: `[object Undefined]`
141-
- For arrays: `[object Array]`
142-
- ...etc (customizable).
144+
- Para un número, será `[object Number]`
145+
- Para un booleano, será `[objetc Boolean]`
146+
- Para `null`: `[objetc Null]`
147+
- Para `undefined`: `[objetc Undefined]`
148+
- Para matrices: `[Object Array]`
149+
- ... etc (personalizable).
143150

144-
Let's demonstrate:
151+
Demostremos:
145152

146153
```js run
147-
// copy toString method into a variable for convenience
154+
// copie el método toString en una variable a conveniencia
148155
let objectToString = Object.prototype.toString;
149156

150-
// what type is this?
157+
// ¿que tipo es este?
151158
let arr = [];
152159

153-
alert( objectToString.call(arr) ); // [object Array]
160+
alert( objectToString.call(arr) ); // [object *!*Array*/!*]
154161
```
155162

156-
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+
Aquí usamos [call](mdn:js/function/call) como se describe en el capítulo [](info:call-apply-decorators) para ejecutar la función `objectToString` en el contexto `this=arr`.
157164

158-
Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
165+
Internamente, el algoritmo `toString` examina `this` y devuelve el resultado correspondiente. Más ejemplos:
159166

160167
```js run
161168
let s = Object.prototype.toString;
@@ -167,9 +174,9 @@ alert( s.call(alert) ); // [object Function]
167174

168175
### Symbol.toStringTag
169176

170-
The behavior of Object `toString` can be customized using a special object property `Symbol.toStringTag`.
177+
El comportamiento del objeto `toString` se puede personalizar utilizando una propiedad de objeto especial `Symbol.toStringTag`.
171178

172-
For instance:
179+
Por ejemplo:
173180

174181
```js run
175182
let user = {
@@ -179,33 +186,33 @@ let user = {
179186
alert( {}.toString.call(user) ); // [object User]
180187
```
181188

182-
For most environment-specific objects, there is such a property. Here are few browser specific examples:
189+
Para la mayoría de los objetos específicos del entorno, existe dicha propiedad. Aquí hay algunos ejemplos específicos del navegador:
183190

184191
```js run
185-
// toStringTag for the envinronment-specific object and class:
186-
alert( window[Symbol.toStringTag]); // window
192+
// ttoStringTag para el objeto y clase específicos del entorno:
193+
alert( window[Symbol.toStringTag]); // ventana
187194
alert( XMLHttpRequest.prototype[Symbol.toStringTag] ); // XMLHttpRequest
188195

189196
alert( {}.toString.call(window) ); // [object Window]
190197
alert( {}.toString.call(new XMLHttpRequest()) ); // [object XMLHttpRequest]
191198
```
192199

193-
As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped into `[object ...]`.
200+
Como puedes ver, el resultado es exactamente `Symbol.toStringTag` (si existe), envuelto en `[objetc ...]`.
194201

195-
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+
Al final tenemos "typeof con esteroides" que no solo funciona para tipos de datos primitivos, sino también para objetos incorporados e incluso puede personalizarse.
196203

197-
It can be used 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` en lugar de `instanceof` para los objetos incorporados cuando deseamos obtener el tipo como una cadena en lugar de solo verificar.
198205

199-
## Summary
206+
## Resumen
200207

201-
Let's recap the type-checking methods that we know:
208+
Resumamos los métodos de verificación de tipos que conocemos:
202209

203-
| | works for | returns |
210+
| | trabaja para | retorna |
204211
|---------------|-------------|---------------|
205-
| `typeof` | primitives | string |
206-
| `{}.toString` | primitives, built-in objects, objects with `Symbol.toStringTag` | string |
207-
| `instanceof` | objects | true/false |
212+
| `typeof` | primitivos | cadena |
213+
| `{}.toString` | primitivos, objetos incorporados, objetos con `Symbol.toStringTag` | cadena |
214+
| `instanceof` | objetos | true/false |
208215

209-
As we can see, `{}.toString` is technically a "more advanced" `typeof`.
216+
Como podemos ver, `{}.toString` es técnicamente un `typeof` "más avanzado".
210217

211-
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+
Y el operador `instanceof` realmente brilla cuando estamos trabajando con una jerarquía de clases y queremos verificar si la clase tiene en cuenta la herencia.

0 commit comments

Comments
 (0)