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
Built-in classes like Array, Map and others are extendable also.
4
+
Las clases integradas como Array, Map y otras también son extensibles.
5
5
6
-
For instance, here`PowerArray`inherits from the native`Array`:
6
+
Por ejemplo, aquí`PowerArray`hereda del nativo`Array`:
7
7
8
8
```js run
9
-
//add one more method to it (can do more)
9
+
//se agrega un método más (puedes hacer más)
10
10
classPowerArrayextendsArray {
11
11
isEmpty() {
12
12
returnthis.length===0;
13
13
}
14
14
}
15
15
16
16
let arr =newPowerArray(1, 2, 5, 10, 50);
17
-
alert(arr.isEmpty()); //false
17
+
alert(arr.isEmpty()); //falso
18
18
19
19
let filteredArr =arr.filter(item=> item >=10);
20
20
alert(filteredArr); // 10, 50
21
-
alert(filteredArr.isEmpty()); //false
21
+
alert(filteredArr.isEmpty()); //falso
22
22
```
23
23
24
-
Please note a very interesting thing. Built-in methods like`filter`, `map`and others -- return new objects of exactly the inherited type. They rely on the `constructor`property to do so.
24
+
Tenga en cuenta una cosa muy interesante. Métodos incorporados como`filter`, `map`y otros: devuelven nuevos objetos exactamente del tipo heredado `PowerArray`. Su implementación interna utiliza la propiedad `constructor`del objeto para eso.
25
25
26
-
In the example above,
26
+
En el ejemplo anterior,
27
27
```js
28
28
arr.constructor=== PowerArray
29
29
```
30
30
31
-
So when `arr.filter()` is called, it internally creates the new array of results exactly as `new PowerArray`.
32
-
That's actually very cool, because we can keep using `PowerArray` methods further on the result.
31
+
Cuando se llama a `arr.filter()`, crea internamente la nueva matriz de resultados usando exactamente `arr.constructor`, no el básico `Array`. En realidad, eso es muy bueno, porque podemos seguir usando métodos `PowerArray` más adelante en el resultado.
33
32
34
-
Even more, we can customize that behavior.
33
+
Aún más, podemos personalizar ese comportamiento.
35
34
36
-
There's a special static getter`Symbol.species`, if exists, it returns the constructor to use in such cases.
35
+
Podemos agregar un `getter` estático especial `Symbol.species` a la clase. Si existe, debería devolver el constructor que JavaScript usará internamente para crear nuevas entidades en `map`, `filter` y así sucesivamente.
37
36
38
-
If we'd like built-in methods like `map`, `filter`will return regular arrays, we can return `Array`in`Symbol.species`, like here:
37
+
Si queremos que los métodos incorporados como `map` o `filter`devuelvan matrices regulares, podemos devolver `Array`en`Symbol.species`, como aquí:
39
38
40
39
```js run
41
40
classPowerArrayextendsArray {
@@ -44,39 +43,47 @@ class PowerArray extends Array {
44
43
}
45
44
46
45
*!*
47
-
//built-in methods will use this as the constructor
46
+
//los métodos incorporados usarán esto como el constructor
48
47
staticget [Symbol.species]() {
49
48
returnArray;
50
49
}
51
50
*/!*
52
51
}
53
52
54
53
let arr =newPowerArray(1, 2, 5, 10, 50);
55
-
alert(arr.isEmpty()); //false
54
+
alert(arr.isEmpty()); //falso
56
55
57
-
// filter creates new array using arr.constructor[Symbol.species] as constructor
56
+
// filter crea una nueva matriz usando arr.constructor[Symbol.species] como constructor
58
57
let filteredArr =arr.filter(item=> item >=10);
59
58
60
59
*!*
61
-
//filteredArr is not PowerArray, but Array
60
+
//filterArr no es PowerArray, sino Array
62
61
*/!*
63
-
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
62
+
alert(filteredArr.isEmpty()); // Error: filterArr.isEmpty no es una función
64
63
```
65
64
66
-
As you can see, now`.filter`returns`Array`. So the extended functionality is not passed any further.
65
+
Como puede ver, ahora`.filter`devuelve`Array`. Por lo tanto, la funcionalidad extendida ya no se pasa.
Otras colecciones, como `Map` y `Set`, funcionan igual. También usan `Symbol.species`.
69
+
```
70
+
71
+
## Sin herencia estática en incorporados
69
72
70
-
Built-in objects have their own static methods, for instance`Object.keys`, `Array.isArray` etc.
73
+
Los objetos incorporados tienen sus propios métodos estáticos, por ejemplo,`Object.keys`, `Array.isArray`, etc.
71
74
72
-
And we've already been talking about native classes extending each other: `Array.[[Prototype]] = Object`.
75
+
Como ya sabemos, las clases nativas se extienden entre sí. Por ejemplo, `Array` extiende `Object`.
73
76
74
-
But statics are an exception. Built-in classes don't inherit static properties from each other.
77
+
Normalmente, cuando una clase extiende a otra, se heredan los métodos estáticos y no estáticos. Eso se explicó a fondo en el artículo [](info:static-properties-methods#statics-and-inheritance).
75
78
76
-
In other words, the prototype of built-in constructor `Array` does not point to `Object`. This way `Array` and `Date` do not have `Array.keys` or `Date.keys`. And that feels natural.
79
+
Pero las clases integradas son una excepción. No heredan estáticos el uno del otro.
77
80
78
-
Here's the picture structure for `Date` and `Object`:
81
+
Por ejemplo, tanto `Array` como `Date` heredan de `Object`, por lo que sus instancias tienen métodos de `Object.prototype`. Pero `Array.[[Prototype]]` no hace referencia a `Object`, por lo que no existe, por ejemplo, el método estático `Array.keys()` (o `Date.keys()`).
82
+
83
+
Aquí está la imagen, estructura para `Date` y `Object`:
79
84
80
85

81
86
82
-
Note, there's no link between `Date` and `Object`. Both `Object` and `Date` exist independently. `Date.prototype` inherits from `Object.prototype`, but that's all.
87
+
Como puede ver, no hay un vínculo entre `Date` y `Object`. Son independientes, solo `Date.prototype` hereda de `Object.prototype`.
88
+
89
+
Esa es una diferencia importante de herencia entre los objetos integrados en comparación con lo que obtenemos con 'extends`.
0 commit comments