From 15fb132153cd764cc53d43f5b50fdaf7556e584f Mon Sep 17 00:00:00 2001 From: Carlos Ortiz Gutierrez Date: Fri, 8 May 2020 19:42:38 -0600 Subject: [PATCH] 1-09-05 Traducido 4 --- 1-js/09-classes/05-extend-natives/article.md | 59 ++++++++------- .../object-date-inheritance.svg | 72 +------------------ 2 files changed, 34 insertions(+), 97 deletions(-) diff --git a/1-js/09-classes/05-extend-natives/article.md b/1-js/09-classes/05-extend-natives/article.md index 4cf1c2bdd..c2195c510 100644 --- a/1-js/09-classes/05-extend-natives/article.md +++ b/1-js/09-classes/05-extend-natives/article.md @@ -1,12 +1,12 @@ -# Extending built-in classes +# Ampliación de clases integradas -Built-in classes like Array, Map and others are extendable also. +Las clases integradas como Array, Map y otras también son extensibles. -For instance, here `PowerArray` inherits from the native `Array`: +Por ejemplo, aquí `PowerArray` hereda del nativo `Array`: ```js run -// add one more method to it (can do more) +// se agrega un método más (puedes hacer más) class PowerArray extends Array { isEmpty() { return this.length === 0; @@ -14,28 +14,27 @@ class PowerArray extends Array { } let arr = new PowerArray(1, 2, 5, 10, 50); -alert(arr.isEmpty()); // false +alert(arr.isEmpty()); // falso let filteredArr = arr.filter(item => item >= 10); alert(filteredArr); // 10, 50 -alert(filteredArr.isEmpty()); // false +alert(filteredArr.isEmpty()); // falso ``` -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. +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. -In the example above, +En el ejemplo anterior, ```js arr.constructor === PowerArray ``` -So when `arr.filter()` is called, it internally creates the new array of results exactly as `new PowerArray`. -That's actually very cool, because we can keep using `PowerArray` methods further on the result. +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. -Even more, we can customize that behavior. +Aún más, podemos personalizar ese comportamiento. -There's a special static getter `Symbol.species`, if exists, it returns the constructor to use in such cases. +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. -If we'd like built-in methods like `map`, `filter` will return regular arrays, we can return `Array` in `Symbol.species`, like here: +Si queremos que los métodos incorporados como `map` o `filter` devuelvan matrices regulares, podemos devolver `Array` en `Symbol.species`, como aquí: ```js run class PowerArray extends Array { @@ -44,7 +43,7 @@ class PowerArray extends Array { } *!* - // built-in methods will use this as the constructor + // los métodos incorporados usarán esto como el constructor static get [Symbol.species]() { return Array; } @@ -52,31 +51,39 @@ class PowerArray extends Array { } let arr = new PowerArray(1, 2, 5, 10, 50); -alert(arr.isEmpty()); // false +alert(arr.isEmpty()); // falso -// filter creates new array using arr.constructor[Symbol.species] as constructor +// filter crea una nueva matriz usando arr.constructor[Symbol.species] como constructor let filteredArr = arr.filter(item => item >= 10); *!* -// filteredArr is not PowerArray, but Array +// filterArr no es PowerArray, sino Array */!* -alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function +alert(filteredArr.isEmpty()); // Error: filterArr.isEmpty no es una función ``` -As you can see, now `.filter` returns `Array`. So the extended functionality is not passed any further. +Como puede ver, ahora `.filter` devuelve `Array`. Por lo tanto, la funcionalidad extendida ya no se pasa. -## No static inheritance in built-ins +```smart header="Other collections trabaja similarmente" +Otras colecciones, como `Map` y `Set`, funcionan igual. También usan `Symbol.species`. +``` + +## Sin herencia estática en incorporados -Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray` etc. +Los objetos incorporados tienen sus propios métodos estáticos, por ejemplo, `Object.keys`, `Array.isArray`, etc. -And we've already been talking about native classes extending each other: `Array.[[Prototype]] = Object`. +Como ya sabemos, las clases nativas se extienden entre sí. Por ejemplo, `Array` extiende `Object`. -But statics are an exception. Built-in classes don't inherit static properties from each other. +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). -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. +Pero las clases integradas son una excepción. No heredan estáticos el uno del otro. -Here's the picture structure for `Date` and `Object`: +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()`). + +Aquí está la imagen, estructura para `Date` y `Object`: ![](object-date-inheritance.svg) -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. +Como puede ver, no hay un vínculo entre `Date` y `Object`. Son independientes, solo `Date.prototype` hereda de `Object.prototype`. + +Esa es una diferencia importante de herencia entre los objetos integrados en comparación con lo que obtenemos con 'extends`. diff --git a/1-js/09-classes/05-extend-natives/object-date-inheritance.svg b/1-js/09-classes/05-extend-natives/object-date-inheritance.svg index f46577f14..470aabf7f 100644 --- a/1-js/09-classes/05-extend-natives/object-date-inheritance.svg +++ b/1-js/09-classes/05-extend-natives/object-date-inheritance.svg @@ -1,71 +1 @@ - - - - object-date-inheritance.svg - Created with sketchtool. - - - - - constructor: Object - toString: function - hasOwnProperty: function - ... - - - - Object.prototype - - - - constructor: Date - toString: function - getDate: function - ... - - - Date.prototype - - - - Object - - - - Date - - - new Date() - - - - - [[Prototype]] - - - - [[Prototype]] - - - prototype - - - - prototype - - - defineProperty - keys - ... - - - now - parse - ... - - - 1 Jan 2019 - - - - \ No newline at end of file +constructor: Object toString: function hasOwnProperty: function ...Object.prototypeconstructor: Date toString: function getDate: function ...Date.prototypeObjectDatenew Date()[[Prototype]][[Prototype]]prototypeprototypedefineProperty keys ...now parse ...1 Jan 2019 \ No newline at end of file