Skip to content

Commit d43daf7

Browse files
authored
Merge pull request #413 from danilolmc/builtin-classes
Extending built-in classes
2 parents bb54132 + f06d644 commit d43daf7

File tree

1 file changed

+26
-26
lines changed

1 file changed

+26
-26
lines changed
+26-26
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11

2-
# Extending built-in classes
2+
# Estendendo classes nativas
33

4-
Built-in classes like Array, Map and others are extendable also.
4+
Classes nativas como Array, Map e outras também podem ser estendidas.
55

6-
For instance, here `PowerArray` inherits from the native `Array`:
6+
Por exemplo, aqui `PowerArray` herda do `Array` nativo:
77

88
```js run
9-
// add one more method to it (can do more)
9+
// adiciona mais um método (pode fazer mais)
1010
class PowerArray extends Array {
1111
isEmpty() {
1212
return this.length === 0;
@@ -21,20 +21,20 @@ alert(filteredArr); // 10, 50
2121
alert(filteredArr.isEmpty()); // false
2222
```
2323

24-
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.
24+
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.
2525

26-
In the example above,
26+
No exemplo acima,
2727
```js
2828
arr.constructor === PowerArray
2929
```
3030

31-
When `arr.filter()` is called, it internally creates the new array of results using exactly `arr.constructor`, not basic `Array`. That's actually very cool, because we can keep using `PowerArray` methods further on the result.
31+
Quando `arr.filter()` é chamado, ele internamente cria o novo array de 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.
3232

33-
Even more, we can customize that behavior.
33+
Ainda mais, podemos personalizar este comportamento.
3434

35-
We can add a special static getter `Symbol.species` to the class. If it exists, it should return the constructor that JavaScript will use internally to create new entities in `map`, `filter` and so on.
35+
Podemos adicionar um getter estático especial chamado `Symbol.species` à classe. Se ele existir, deve retornar o construtor que o JavaScript usará internamente para criar novas entidades em `map`, `filter` e assim por diante.
3636

37-
If we'd like built-in methods like `map` or `filter` to return regular arrays, we can return `Array` in `Symbol.species`, like here:
37+
Se quisermos que os métodos nativos como `map` ou `filter` retornem arrays regulares, podemos retornar `Array` em `Symbol.species`, como nesse exemplo:
3838

3939
```js run
4040
class PowerArray extends Array {
@@ -43,7 +43,7 @@ class PowerArray extends Array {
4343
}
4444

4545
*!*
46-
// built-in methods will use this as the constructor
46+
// métodos nativos usarão isso como o construtor
4747
static get [Symbol.species]() {
4848
return Array;
4949
}
@@ -53,37 +53,37 @@ class PowerArray extends Array {
5353
let arr = new PowerArray(1, 2, 5, 10, 50);
5454
alert(arr.isEmpty()); // false
5555

56-
// filter creates new array using arr.constructor[Symbol.species] as constructor
57-
let filteredArr = arr.filter(item => item >= 10);
56+
// filter cria um novo array usando arr.constructor[Symbol.species] como constructor
57+
let filteredArr = arr.filter(item => item >= 10);
5858

5959
*!*
60-
// filteredArr is not PowerArray, but Array
60+
// filteredArr não é PowerArray, mas Array
6161
*/!*
6262
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
6363
```
6464

65-
As you can see, now `.filter` returns `Array`. So the extended functionality is not passed any further.
65+
Como você pode ver, agora `.filter` retorna `Array`. Assim, a funcionalidade estendida não é repassada adiante.
6666

67-
```smart header="Other collections work similarly"
68-
Other collections, such as `Map` and `Set`, work alike. They also use `Symbol.species`.
67+
```smart header="Outras coleções funcionam similarmente"
68+
Outras coleções, como `Map` e `Set, funcionam da mesma forma. Elas também utilizam `Symbol.species`.
6969
```
7070

71-
## No static inheritance in built-ins
71+
## Sem herança estática em objetos nativos
7272

73-
Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray` etc.
73+
Objetos nativos possuem seus próprios métodos estáticos, por exemplo `Object.keys`, `Array.isArray`, etc.
7474

75-
As we already know, native classes extend each other. For instance, `Array` extends `Object`.
75+
Como já sabemos, classes nativas se estendem. Por exemplo, `Array` estende de `Object`.
7676

77-
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).
77+
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).
7878

79-
But built-in classes are an exception. They don't inherit statics from each other.
79+
Mas as classes nativas são uma exceção. Elas não herdam métodos estáticos uma das outras.
8080

81-
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.
81+
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()`).
8282

83-
Here's the picture structure for `Date` and `Object`:
83+
Aqui está a estrutura visual para `Date` e `Object`:
8484

8585
![](object-date-inheritance.svg)
8686

87-
As you can see, there's no link between `Date` and `Object`. They are independent, only `Date.prototype` inherits from `Object.prototype`.
87+
Como você pode ver, não existe ligação entre `Date` e `Object`. Eles são independentes, apenas `Date.prototype` herda de `Object.prototype`.
8888

89-
That's an important difference of inheritance between built-in objects compared to what we get with `extends`.
89+
Essa é uma diferença importante de herança entre objetos nativos em comparação com o que obtemos com `extends`.

0 commit comments

Comments
 (0)