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
+
El operador `instanceof`permite verificar si un objeto pertenece a una clase determinada. También tiene en cuenta la herencia.
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
+
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.
6
6
7
-
## The instanceof operator[#ref-instanceof]
7
+
## El operador instanceof[#ref-instanceof]
8
8
9
-
The syntax is:
9
+
La sintaxis es:
10
10
```js
11
11
obj instanceof Class
12
12
```
13
+
Devuelve `true` si `obj` pertenece a la `Class` o una clase que hereda de ella.
13
14
14
-
It returns `true` if `obj` belongs to the `Class` or a class inheriting from it.
Please note that `arr`also belongs to the `Object` class. That's because `Array`prototypically inherits from`Object`.
46
+
Tenga en cuenta que `arr`también pertenece a la clase `Object`. Esto se debe a que `Array`hereda prototípicamente de`Object`.
48
47
49
-
Normally, `instanceof`examines the prototype chain for the check. We can also set a custom logic in the static method`Symbol.hasInstance`.
48
+
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`.
50
49
51
-
The algorithm of`obj instanceof Class`works roughly as follows:
50
+
El algoritmo de`obj instanceof Class`funciona más o menos de la siguiente manera:
52
51
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`.
52
+
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
53
55
-
For example:
54
+
Por ejemplo:
56
55
57
56
```js run
58
-
// setup instanceOf check that assumes that
59
-
// anything with canEat property is an animal
57
+
// Instalar instancia de verificación que asume que
58
+
// cualquier cosa con propiedad canEat es un animal
59
+
60
60
classAnimal {
61
61
static [Symbol.hasInstance](obj) {
62
62
if (obj.canEat) returntrue;
@@ -65,104 +65,105 @@ 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); //verdadero: Animal[Symbol.hasInstance](obj) es llamada
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. 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`.
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
103
+
Aquí está la ilustración de lo que `rabbit instanceof Animal`compara con`Animal.prototype`:
103
104
104
105

105
106
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)`.
107
+
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)`.
107
108
108
-
It's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
109
+
Es divertido, ¡pero el constructor `Class` en sí mismo no participa en el chequeo! Solo importa la cadena de prototipos y `Class.prototype`.
109
110
110
-
That can lead to interesting consequences when a `prototype` property is changed after the object is created.
111
+
Eso puede llevar a consecuencias interesantes cuando se cambia una propiedad `prototype` después de crear el objeto.
111
112
112
-
Like here:
113
+
Como aquí:
113
114
114
115
```js run
115
116
functionRabbit() {}
116
117
let rabbit =newRabbit();
117
118
118
-
// changed the prototype
119
+
//cambió el prototipo
119
120
Rabbit.prototype= {};
120
121
121
-
// ...not a rabbit any more!
122
+
// ...ya no es un conejo!
122
123
*!*
123
-
alert( rabbit instanceof Rabbit ); // false
124
+
alert( rabbit instanceof Rabbit ); //falso
124
125
*/!*
125
126
```
126
127
127
-
## Bonus: Object.prototype.toString for the type
128
+
## Bonificación: Object.prototype.toString para el tipo
128
129
129
-
We already know that plain objects are converted to string as `[object Object]`:
130
+
Ya sabemos que los objetos simples se convierten en cadenas como`[objetc Objetc]`:
130
131
131
132
```js run
132
133
let obj = {};
133
134
134
135
alert(obj); // [object Object]
135
-
alert(obj.toString()); // the same
136
+
alert(obj.toString()); //lo mismo
136
137
```
137
138
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`.
139
+
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`.
139
140
140
-
Sounds strange? Indeed. Let's demystify.
141
+
¿Suena extraño? En efecto. Vamos a desmitificar.
141
142
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.
143
+
Por esta [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.
143
144
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).
145
+
-Para un número, será`[object Number]`
146
+
-Para un booleano, será `[objetc Boolean]`
147
+
-Para`null`: `[objetc Null]`
148
+
-Para`undefined`: `[objetc Undefined]`
149
+
-Para matrices: `[Object Array]`
150
+
- ...etc (personalizable).
150
151
151
-
Let's demonstrate:
152
+
Demostremos:
152
153
153
154
```js run
154
-
// copy toString method into a variable for convenience
155
+
//copie el método toString en una variable a conveniencia
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`.
164
+
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`.
164
165
165
-
Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
166
+
Internamente, el algoritmo `toString`examina `this`y devuelve el resultado correspondiente. Más ejemplos:
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`[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
+
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.
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`en lugar de `instanceof`para los objetos incorporados cuando deseamos obtener el tipo como una cadena en lugar de solo verificar.
205
205
206
-
## Summary
206
+
## Resumen
207
207
208
-
Let's summarize the type-checking methods that we know:
208
+
Resumamos los métodos de verificación de tipos que conocemos:
As we can see, `{}.toString`is technically a "more advanced"`typeof`.
216
+
Como podemos ver, `{}.toString`es técnicamente un `typeof` "más avanzado".
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
+
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