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
13
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.
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`.
48
48
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`.
50
50
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:
52
52
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:
54
56
55
57
```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
57
60
classAnimal {
58
61
static [Symbol.hasInstance](obj) {
59
62
if (obj.canEat) returntrue;
60
63
}
61
64
}
62
65
63
66
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
65
69
```
66
70
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`.
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`:
94
103
95
104

96
105
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)`.
98
107
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`.
100
109
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.
102
111
103
-
Like here:
112
+
Como aquí:
104
113
105
114
```js run
106
115
functionRabbit() {}
107
116
let rabbit =newRabbit();
108
117
109
-
// changed the prototype
118
+
//cambió el prototipo
110
119
Rabbit.prototype= {};
111
120
112
-
// ...not a rabbit any more!
121
+
// ...ya no es un conejo!
113
122
*!*
114
-
alert( rabbit instanceof Rabbit ); // false
123
+
alert( rabbit instanceof Rabbit ); //falso
115
124
*/!*
116
125
```
117
126
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
121
128
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]`:
123
130
124
131
```js run
125
132
let obj = {};
126
133
127
134
alert(obj); // [object Object]
128
-
alert(obj.toString()); // the same
135
+
alert(obj.toString()); //lo mismo
129
136
```
130
137
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`.
132
139
133
-
Sounds strange?Indeed. Let's demystify.
140
+
¿Suena extraño? En efecto. Vamos a desmitificar.
134
141
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.
136
143
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).
143
150
144
-
Let's demonstrate:
151
+
Demostremos:
145
152
146
153
```js run
147
-
// copy toString method into a variable for convenience
154
+
//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`.
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`.
157
164
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:
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 ...]`.
194
201
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.
196
203
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.
198
205
199
-
## Summary
206
+
## Resumen
200
207
201
-
Let's recap 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".
210
217
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