Skip to content

Commit 7efd333

Browse files
committed
Merge branch 'master' of github.com:danilolmc/pt.javascript.info into update-dynamic-imports
2 parents 891f42b + 123d22a commit 7efd333

File tree

9 files changed

+228
-230
lines changed

9 files changed

+228
-230
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`.

1-js/99-js-misc/05-bigint/article.md

+44-45
Original file line numberDiff line numberDiff line change
@@ -1,130 +1,129 @@
11
# BigInt
22

3-
[recent caniuse="bigint"]
3+
[BigInt recentemente adicionado ao caniuse="bigint"]
44

5-
`BigInt` is a special numeric type that provides support for integers of arbitrary length.
5+
BigInt é um tipo numérico especial que oferece suporte para inteiros de tamanho arbitrário.
66

7-
A bigint is created by appending `n` to the end of an integer literal or by calling the function `BigInt` that creates bigints from strings, numbers etc.
7+
Um bigint é criado anexando `n` ao final de um literal inteiro ou chamando a função `BigInt` que cria BigInts a partir de strings, números, etc.
88

99
```js
1010
const bigint = 1234567890123456789012345678901234567890n;
1111

1212
const sameBigint = BigInt("1234567890123456789012345678901234567890");
1313

14-
const bigintFromNumber = BigInt(10); // same as 10n
14+
const bigintFromNumber = BigInt(10); // o mesmo que 10n
1515
```
1616

17-
## Math operators
17+
## Operadores matemáticos
1818

19-
`BigInt` can mostly be used like a regular number, for example:
19+
`BigInt` pode ser usado principalmente como um número comum, por exemplo:
2020

2121
```js run
2222
alert(1n + 2n); // 3
2323

2424
alert(5n / 2n); // 2
2525
```
2626

27-
Please note: the division `5/2` returns the result rounded towards zero, without the decimal part. All operations on bigints return bigints.
27+
Perceba: a divisão `5/2` retorna o resultado arredondado para zero, sem a parte decimal. Todas as operações com BigInts retornam BigInts.
2828

29-
We can't mix bigints and regular numbers:
29+
Não podemos misturar BigInts e números comuns:
3030

3131
```js run
32-
alert(1n + 2); // Error: Cannot mix BigInt and other types
32+
alert(1n + 2); // Erro: Não é possível misturar BigInt e outros tipos
3333
```
3434

35-
We should explicitly convert them if needed: using either `BigInt()` or `Number()`, like this:
35+
Devemos convertê-los explicitamente, se necessário, usando `BigInt()` ou `Number()`, assim:
3636

3737
```js run
3838
let bigint = 1n;
3939
let number = 2;
4040

41-
// number to bigint
41+
// number para bigint
4242
alert(bigint + BigInt(number)); // 3
4343

44-
// bigint to number
44+
// bigint para number
4545
alert(Number(bigint) + number); // 3
4646
```
4747

48-
The conversion operations are always silent, never give errors, but if the bigint is too huge and won't fit the number type, then extra bits will be cut off, so we should be careful doing such conversion.
48+
As operações de conversão são sempre silenciosas, nunca dão erros, mas se o bigint for muito grande e não couber no tipo número, então bits extras serão cortados, então devemos ter cuidado ao fazer a conversão.
4949

50-
````smart header="The unary plus is not supported on bigints"
51-
The unary plus operator `+value` is a well-known way to convert `value` to a number.
50+
````smart header="O operador mais unário não é suportado em BigInts"
51+
O operador mais unário `+valor` é uma maneira bem conhecida de converter `valor` para um número.
5252
53-
In order to avoid confusion, it's not supported on bigints:
53+
Para evitar confusão, não é suportado em BigInts:
5454
```js run
5555
let bigint = 1n;
5656
57-
alert( +bigint ); // error
57+
alert( +bigint ); // erro
5858
```
59-
So we should use `Number()` to convert a bigint to a number.
59+
Então, devemos usar `Number()` para converter um BigInt em um número.
6060
````
6161

62-
## Comparisons
62+
## Comparações
6363

64-
Comparisons, such as `<`, `>` work with bigints and numbers just fine:
64+
Comparações, como `<`, `>` funcionam bem com BigInts e números:
6565

6666
```js run
6767
alert( 2n > 1n ); // true
6868

6969
alert( 2n > 1 ); // true
7070
```
7171

72-
Please note though, as numbers and bigints belong to different types, they can be equal `==`, but not strictly equal `===`:
72+
Note que, como números e BigInts pertencem a tipos diferentes, eles podem ser iguais `==`, mas não estritamente iguais `===`:
7373

7474
```js run
7575
alert( 1 == 1n ); // true
7676

7777
alert( 1 === 1n ); // false
7878
```
7979

80-
## Boolean operations
80+
## Operações booleanas
8181

82-
When inside `if` or other boolean operations, bigints behave like numbers.
82+
Quando dentro de `if` ou outras operações booleanas, BigInts se comportam como números.
8383

84-
For instance, in `if`, bigint `0n` is falsy, other values are truthy:
84+
Por exemplo, em `if`, o bigint `0n` é falso, outros valores são verdadeiros:
8585

8686
```js run
8787
if (0n) {
88-
// never executes
88+
// nunca executa
8989
}
9090
```
91-
92-
Boolean operators, such as `||`, `&&` and others also work with bigints similar to numbers:
91+
Operadores booleanos, como `||`, `&&` e outros também funcionam com BigInts semelhante aos números:
9392

9493
```js run
95-
alert( 1n || 2 ); // 1 (1n is considered truthy)
94+
alert( 1n || 2 ); // 1 (1n é considerado verdadeiro)
9695

97-
alert( 0n || 2 ); // 2 (0n is considered falsy)
96+
alert( 0n || 2 ); // 2 (0n é considerado falso)
9897
```
9998

10099
## Polyfills
101100

102-
Polyfilling bigints is tricky. The reason is that many JavaScript operators, such as `+`, `-` and so on behave differently with bigints compared to regular numbers.
101+
Fazer um polyfill para BigInts é complicado. A razão é que muitos operadores JavaScript, como `+`, `-` e assim por diante se comportam de maneira diferente com BigInts em comparação com números regulares.
103102

104-
For example, division of bigints always returns a bigint (rounded if necessary).
103+
Por exemplo, a divisão de BigInts sempre retorna um bigint (arredondado se necessário).
105104

106-
To emulate such behavior, a polyfill would need to analyze the code and replace all such operators with its functions. But doing so is cumbersome and would cost a lot of performance.
105+
Para emular tal comportamento, um polyfill precisaria analisar o código e substituir todos esses operadores com suas funções. Mas fazer isso é trabalhoso e custaria muito em termos de desempenho.
107106

108-
So, there's no well-known good polyfill.
107+
Então, não há um polyfill bem conhecido e bom.
109108

110-
Although, the other way around is proposed by the developers of [JSBI](https://github.com/GoogleChromeLabs/jsbi) library.
109+
Apesar disso, o caminho inverso é proposto pelos desenvolvedores da biblioteca [JSBI](https://github.com/GoogleChromeLabs/jsbi).
111110

112-
This library implements big numbers using its own methods. We can use them instead of native bigints:
111+
Esta biblioteca implementa números grandes usando seus próprios métodos. Podemos usá-los em vez de BigInts nativos:
113112

114-
| Operation | native `BigInt` | JSBI |
113+
| Operação | `BigInt` nativo | JSBI |
115114
|-----------|-----------------|------|
116-
| Creation from Number | `a = BigInt(789)` | `a = JSBI.BigInt(789)` |
117-
| Addition | `c = a + b` | `c = JSBI.add(a, b)` |
118-
| Subtraction | `c = a - b` | `c = JSBI.subtract(a, b)` |
115+
| Criação a partir de Number | `a = BigInt(789)` | `a = JSBI.BigInt(789)` |
116+
| Adição | `c = a + b` | `c = JSBI.add(a, b)` |
117+
| Subtração | `c = a - b` | `c = JSBI.subtract(a, b)` |
119118
| ... | ... | ... |
120119

121-
...And then use the polyfill (Babel plugin) to convert JSBI calls to native bigints for those browsers that support them.
120+
...E então use o polyfill (plugin do Babel) para converter chamadas JSBI para BigInts nativos para aqueles navegadores que os suportam.
122121

123-
In other words, this approach suggests that we write code in JSBI instead of native bigints. But JSBI works with numbers as with bigints internally, emulates them closely following the specification, so the code will be "bigint-ready".
122+
Em outras palavras, essa abordagem sugere que escrevamos código em JSBI em vez de BigInts nativos. Mas o JSBI trabalha com números como se fossem BigInts internamente, emula-os de perto seguindo a especificação, então o código será "pronto para bigint".
124123

125-
We can use such JSBI code "as is" for engines that don't support bigints and for those that do support - the polyfill will convert the calls to native bigints.
124+
Podemos usar esse código JSBI "como está" para motores que não suportam BigInts e para aqueles que suportam - o polyfill converterá as chamadas para BigInts nativos.
126125

127-
## References
126+
## Referências
128127

129-
- [MDN docs on BigInt](mdn:/JavaScript/Reference/Global_Objects/BigInt).
130-
- [Specification](https://tc39.es/ecma262/#sec-bigint-objects).
128+
- [Documentação da MDN sobre BigInt](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/BigInt).
129+
- [Especificação](https://tc39.es/ecma262/#sec-bigint-objects).

0 commit comments

Comments
 (0)