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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Built-in classes like Array, Mapand others are extendable also.
Classes nativas como Array, Mape outras também podem ser estendidas.
For instance, here `PowerArray`inherits from the native`Array`:
Por exemplo, aqui `PowerArray`herda do`Array` nativo:
```js run
//add one more method to it (can do more)
//adiciona mais um método (pode fazer mais)
class PowerArray extends Array {
isEmpty() {
return this.length === 0;
Expand All
@@ -21,20 +21,20 @@ alert(filteredArr); // 10, 50
alert(filteredArr.isEmpty()); // false
```
Please note a very interesting thing. Built-in methods like `filter`, `map`and others -- return new objects of exactly the inherited type`PowerArray`.Their internal implementation uses the object's `constructor`property for that.
Note uma coisa muito interessante. Métodos nativos, como `filter`, `map`e outros retornam novos objetos exatamente do tipo herdado`PowerArray`.Sua implementação interna usa a propriedade `constructor`do objeto para isso.
In the example above,
No exemplo acima,
```js
arr.constructor === PowerArray
```
When `arr.filter()`is called, it internally creates the new arrayof results using exactly `arr.constructor`,not basic`Array`.That's actually very cool, because we can keep using`PowerArray`methods further on the result.
Quando `arr.filter()`é chamado, ele internamente cria o novo arrayde resultados usando exatamente `arr.constructor`,não o básico`Array`.Isso é realmente interessante, porque podemos continuar utilizando os métodos de`PowerArray`no resultado.
Even more, we can customize that behavior.
Ainda mais, podemos personalizar este comportamento.
We can add a special static getter `Symbol.species`to the class. If it exists, it should return the constructor that JavaScriptwill use internally to create new entities in`map`, `filter`and so on.
Podemos adicionar um getter estático especial chamado `Symbol.species`à classe. Se ele existir, deve retornar o construtor que o JavaScriptusará internamente para criar novas entidades em`map`, `filter`e assim por diante.
If we'd like built-in methods like`map`or `filter`to return regulararrays, we can return`Array`in `Symbol.species`,like here:
Se quisermos que os métodos nativos como`map`ou `filter`retornemarrays regulares, podemos retornar`Array`em `Symbol.species`,como nesse exemplo:
```js run
class PowerArray extends Array {
Expand All
@@ -43,7 +43,7 @@ class PowerArray extends Array {
}
*!*
//built-in methods will use this as the constructor
//métodos nativos usarão isso como o construtor
static get [Symbol.species]() {
return Array;
}
Expand All
@@ -53,37 +53,37 @@ class PowerArray extends Array {
Outras coleções, como`Map`e `Set, funcionam da mesma forma. Elas também utilizam `Symbol.species`.
```
##No static inheritance in built-ins
##Sem herança estática em objetos nativos
Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray` etc.
Objetos nativos possuem seus próprios métodos estáticos, por exemplo `Object.keys`, `Array.isArray`, etc.
As we already know, nativeclassesextend each other. For instance, `Array`extends `Object`.
Como já sabemos,classesnativas se estendem. Por exemplo, `Array`estende de `Object`.
Normally, when one class extends another, both static and non-static methods are inherited. That was thoroughly explained in the article [](info:static-properties-methods#statics-and-inheritance).
Normalmente, quando uma classe estende outra, métodos estáticos e não estáticos são herdados. Isso foi explicado detalhadamente no artigo [](info:static-properties-methods#statics-and-inheritance).
But built-in classesare an exception. They don't inherit statics from each other.
Mas as classesnativas são uma exceção. Elas não herdam métodos estáticos uma das outras.
For example, both `Array`and `Date`inherit from `Object`,so their instances have methods from `Object.prototype`.But`Array.[[Prototype]]`does not reference`Object`,so there's no, for instance,`Array.keys()` (or `Date.keys()`) static method.
Por exemplo, tanto `Array`quanto `Date`herdam de `Object`,então suas instâncias têm métodos de `Object.prototype`.No entanto`Array.[[Prototype]]`não referencia`Object`,então não existe, por exemplo, um método estático`Array.keys()` (ou `Date.keys()`).
Here's the picture structure for`Date`and `Object`:
Aqui está a estrutura visual para`Date`e `Object`:

As you can see, there's no link between `Date`and `Object`.They are independent, only `Date.prototype`inherits from `Object.prototype`.
Como você pode ver, não existe ligação entre `Date`e `Object`.Eles são independentes, apenas `Date.prototype`herda de `Object.prototype`.
That's an important difference of inheritance between built-in objects compared to what we get with `extends`.
Essa é uma diferença importante de herança entre objetos nativos em comparação com o que obtemos com `extends`.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.