Skip to content

Commit 0f761e8

Browse files
committed
FEAT: Translate native-prototypes (article,tasks & solutions).
1 parent 56a9e45 commit 0f761e8

File tree

5 files changed

+83
-84
lines changed

5 files changed

+83
-84
lines changed

1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ Function.prototype.defer = function(ms) {
66
};
77

88
function f() {
9-
alert("Hello!");
9+
alert("Olá!");
1010
}
1111

12-
f.defer(1000); // shows "Hello!" after 1 sec
12+
f.defer(1000); // mostra "Olá!" depois de 1 segundo
1313
```

1-js/08-prototypes/03-native-prototypes/1-defer-to-prototype/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ importance: 5
22

33
---
44

5-
# Add method "f.defer(ms)" to functions
5+
# Adicione o método "f.defer(ms)" às funções
66

7-
Add to the prototype of all functions the method `defer(ms)`, that runs the function after `ms` milliseconds.
7+
Adicione ao protótipo de todas as funções o método `defer(ms)`, que executa a função depois de `ms` milisegundos.
88

9-
After you do it, such code should work:
9+
Depois de fazer isso, este código deveria funcionar:
1010

1111
```js
1212
function f() {
13-
alert("Hello!");
13+
alert("Olá!");
1414
}
1515

16-
f.defer(1000); // shows "Hello!" after 1 second
16+
f.defer(1000); // mostra "Olá!" depois de 1 segundo
1717
```

1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/solution.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@ Function.prototype.defer = function(ms) {
88
}
99
};
1010

11-
// check it
11+
// confira
1212
function f(a, b) {
1313
alert( a + b );
1414
}
1515

16-
f.defer(1000)(1, 2); // shows 3 after 1 sec
16+
f.defer(1000)(1, 2); // mostra 3 depois de 1 segundo
1717
```
1818

19-
Please note: we use `this` in `f.apply` to make our decoration work for object methods.
19+
Note que: nós usamos `this` no `f.apply` para nossa decoração funcionar para métodos de objetos.
2020

21-
So if the wrapper function is called as an object method, then `this` is passed to the original method `f`.
21+
Então, se a função *wrapper* é chamada como um método de um objeto, então o this é passado para o método `f` original.
2222

2323
```js run
2424
Function.prototype.defer = function(ms) {

1-js/08-prototypes/03-native-prototypes/2-defer-to-prototype-extended/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@ importance: 4
22

33
---
44

5-
# Add the decorating "defer()" to functions
5+
# Adicione o decorador "defer()" às funções
66

7-
Add to the prototype of all functions the method `defer(ms)`, that returns a wrapper, delaying the call by `ms` milliseconds.
7+
Adicione ao protótipo de todas as funções o método `defer(ms)` que retorne um *wrapper* (invólucro), atrasando a chamada em `ms` milisegundos.
88

9-
Here's an example of how it should work:
9+
Aqui está um exemplo de como deveria funcionar:
1010

1111
```js
1212
function f(a, b) {
1313
alert( a + b );
1414
}
1515

16-
f.defer(1000)(1, 2); // shows 3 after 1 second
16+
f.defer(1000)(1, 2); // mostra 3 depois de 1 segundo
1717
```
1818

19-
Please note that the arguments should be passed to the original function.
19+
Note que os argumentos devem ser passados para a função original.
Lines changed: 67 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
1-
# Native prototypes
1+
# Protótipos Nativos
22

3-
The `"prototype"` property is widely used by the core of JavaScript itself. All built-in constructor functions use it.
3+
A propriedade `"prototype"` é comumente utilizada pelo núcleo do próprio JavaScript. Toda função construtora embutida a usa.
44

5-
We'll see how it is for plain objects first, and then for more complex ones.
5+
Vamos ver como é para objetos vazios primeiro, e depois para objetos mais complexos.
66

77
## Object.prototype
88

9-
Let's say we output an empty object:
9+
Digamos que a gente imprima um objeto vazio:
1010

1111
```js run
1212
let obj = {};
1313
alert( obj ); // "[object Object]" ?
1414
```
1515

16-
Where's the code that generates the string `"[object Object]"`? That's a built-in `toString` method, but where is it? The `obj` is empty!
16+
Onde está o código que gera a string `"[object Object]"`? Isso é um método embutido `toString`, mas onde ele está? O `obj` está vazio!
1717

18-
...But the short notation `obj = {}` is the same as `obj = new Object()`, where `Object` is a built-in object constructor function, with its own `prototype` referencing a huge object with `toString` and other methods.
18+
... Mas a notação abreviada `obj = {}` é o mesmo que `obj = new Object()`, onde `Object` é uma função construtora embutida, com seu próprio `prototype` referenciando um objeto enorme com `toString` e outros métodos.
1919

20-
Here's what's going on:
20+
Veja o que está acontecendo:
2121

2222
![](object-prototype.svg)
2323

24-
When `new Object()` is called (or a literal object `{...}` is created), the `[[Prototype]]` of it is set to `Object.prototype` according to the rule that we discussed in the previous chapter:
24+
Quando `new Object()` é chamado (ou um objeto literal `{...}` é criado), o seu `[[Prototype]]` é configurado para o `Object.prototype` de acordo com a regra que nós discutimos no capítulo anterior:
2525

2626
![](object-prototype-1.svg)
2727

28-
So then when `obj.toString()` is called the method is taken from `Object.prototype`.
28+
Assim, quando `obj.toString()` é chamado, o método é obtido de `Object.prototype`.
2929

30-
We can check it like this:
30+
Nós podemos conferir isso assim:
3131

3232
```js run
3333
let obj = {};
@@ -38,115 +38,114 @@ alert(obj.toString === obj.__proto__.toString); //true
3838
alert(obj.toString === Object.prototype.toString); //true
3939
```
4040

41-
Please note that there is no additional `[[Prototype]]` in the chain above `Object.prototype`:
41+
Note que não há um `[[Prototype]]` adicional na cadeia acima de `Object.prototype`:
4242

4343
```js run
4444
alert(Object.prototype.__proto__); // null
4545
```
4646

47-
## Other built-in prototypes
47+
## Outros protótipos embutidos
4848

49-
Other built-in objects such as `Array`, `Date`, `Function` and others also keep methods in prototypes.
49+
Outros objetos embutidos, como `Array`, `Date`, `Function`, entre outros, também mantém métodos nos seus protótipos.
5050

51-
For instance, when we create an array `[1, 2, 3]`, the default `new Array()` constructor is used internally. So the array data is written into the new object, and `Array.prototype` becomes its prototype and provides methods. That's very memory-efficient.
51+
Por exemplo, quando nós criamos um array `[1, 2, 3]`, a função construtura padrão `new Array()` é usada internamente. Dessa forma, os dados são escritos dentro do novo objeto, e `Array.prototype` se torna o seu protótipo e provê métodos. Isso é bem eficiente em termos de memória.
5252

53-
By specification, all of the built-in prototypes have `Object.prototype` on the top. Sometimes people say that "everything inherits from objects".
53+
Pela especificação, todos os protótipos embutidos tem `Object.prototype` no topo. Algumas pessoas dizem que "tudo herda os objetos".
5454

55-
Here's the overall picture (for 3 built-ins to fit):
55+
Aqui temos uma visão geral (para 3 protótipos embutidos):
5656

5757
![](native-prototypes-classes.svg)
5858

59-
Let's check the prototypes manually:
59+
Vamos conferir os protótipos manualmente:
6060

6161
```js run
6262
let arr = [1, 2, 3];
6363

64-
// it inherits from Array.prototype?
64+
// herda de Array.prototype?
6565
alert( arr.__proto__ === Array.prototype ); // true
6666

67-
// then from Object.prototype?
67+
// e depois herda de Object.prototype?
6868
alert( arr.__proto__.__proto__ === Object.prototype ); // true
6969

70-
// and null on the top.
70+
// e null no topo.
7171
alert( arr.__proto__.__proto__.__proto__ ); // null
7272
```
7373

74-
Some methods in prototypes may overlap, for instance, `Array.prototype` has its own `toString` that lists comma-delimited elements:
74+
Alguns métodos nos protótipos podem se sobrepor. Por exemplo, `Array.prototype` tem o seu próprio `toString` que lista os elementos separados por vírgula:
7575

7676
```js run
7777
let arr = [1, 2, 3]
78-
alert(arr); // 1,2,3 <-- the result of Array.prototype.toString
78+
alert(arr); // 1,2,3 <-- O resultado de Array.prototype.toString
7979
```
8080

81-
As we've seen before, `Object.prototype` has `toString` as well, but `Array.prototype` is closer in the chain, so the array variant is used.
81+
Como vimos antes, `Object.prototype` também tem o método `toString`, mas `Array.prototype` está mais perto na cadeia, então a variante da array é utilizada.
8282

8383

8484
![](native-prototypes-array-tostring.svg)
8585

86-
87-
In-browser tools like Chrome developer console also show inheritance (`console.dir` may need to be used for built-in objects):
86+
Ferramentas embutidas em navegadores, como o console do desenvolvedor no Chrome, também mostram herança (objetos embutidos podem precisar usar o `console.dir`):
8887

8988
![](console_dir_array.png)
9089

91-
Other built-in objects also work the same way. Even functions -- they are objects of a built-in `Function` constructor, and their methods (`call`/`apply` and others) are taken from `Function.prototype`. Functions have their own `toString` too.
90+
Outros objetos embutidos também trabalham da mesma forma. Até mesmo funções -- elas são objetos de um construtor `Function` embutido, e seus métodos (`call`/`apply` e outros) são obtidos de `Function.prototype`. Funções também têm seu próprio `toString`.
9291

9392
```js run
9493
function f() {}
9594

9695
alert(f.__proto__ == Function.prototype); // true
97-
alert(f.__proto__.__proto__ == Object.prototype); // true, inherit from objects
96+
alert(f.__proto__.__proto__ == Object.prototype); // true, herdado de object
9897
```
9998

100-
## Primitives
99+
## Primitivos
101100

102-
The most intricate thing happens with strings, numbers and booleans.
101+
As coisas mais complicadas acontecem com strings, números e boleanos.
103102

104-
As we remember, they are not objects. But if we try to access their properties, temporary wrapper objects are created using built-in constructors `String`, `Number` and `Boolean`. They provide the methods and disappear.
103+
Como sabemos, eles não são objetos. Mas se nós tentarmos acessar as propriedades deles, temporariamente são criados objetos que contém os construtores embutidos `String`, `Number` and `Boolean`. Eles fornecem os métodos e disaparecem.
105104

106-
These objects are created invisibly to us and most engines optimize them out, but the specification describes it exactly this way. Methods of these objects also reside in prototypes, available as `String.prototype`, `Number.prototype` and `Boolean.prototype`.
105+
Esses objetos são criados invisivelmente para nós e a maioria das engines otimizam esse processo, apesar da especificação descrevê-lo exatamente dessa forma. Os métodos desses objetos também residem nos protótipos, disponíveis como `String.prototype`, `Number.prototype` e `Boolean.prototype`.
107106

108-
```warn header="Values `null` and `undefined` have no object wrappers"
109-
Special values `null` and `undefined` stand apart. They have no object wrappers, so methods and properties are not available for them. And there are no corresponding prototypes either.
107+
```warn header="Os valores `null` e `undefined` não têm objetos que os envolvam"
108+
O valores especiais `null` e `undefined` se destacam dos outros. Eles não tem objetos que os envolem, então métodos e propriedades não estão disponíveis para eles. Também não existem protótipos correspondentes.
110109
```
111110
112-
## Changing native prototypes [#native-prototype-change]
111+
## Mudando protótipos nativos [#native-prototype-change]
113112
114-
Native prototypes can be modified. For instance, if we add a method to `String.prototype`, it becomes available to all strings:
113+
Protótipos nativos podem ser modificados. Por exemplo, se nós adicionarmos um método a `String.prototype`, ele vai ficar disponível a todas as strings:
115114
116115
```js run
117116
String.prototype.show = function() {
118117
alert(this);
119118
};
120119
121-
"BOOM!".show(); // BOOM!
120+
"BUM!".show(); // BUM!
122121
```
123122

124-
During the process of development, we may have ideas for new built-in methods we'd like to have, and we may be tempted to add them to native prototypes. But that is generally a bad idea.
123+
Durante o processo do desenvolvimento, nós podemos ter novas ideias de métodos embutidos que nós gostaríamos de ter, e podemos ficar tentados a adicioná-los nos protótipos nativos. Mas isso é geralmente uma má ideia.
125124

126125
```warn
127-
Prototypes are global, so it's easy to get a conflict. If two libraries add a method `String.prototype.show`, then one of them will be overwriting the other.
126+
Protótipos são globais, então é fácil gerar um conflito. Se duas bibliotecas adicionam um método `String.prototype.show`, uma delas estará sobrescrevendo a outra.
128127
129-
So, generally, modifying a native prototype is considered a bad idea.
128+
Por isso, geralmente, modificar um protótipo nativo é considerado uma má ideia.
130129
```
131130

132-
**In modern programming, there is only one case where modifying native prototypes is approved. That's polyfilling.**
131+
**Na programação moderna, existe apenas um caso quando modificar protótipos nativos é aprovado: fazer polyfill (polyfilling).**
133132

134-
Polyfilling is a term for making a substitute for a method that exists in the JavaScript specification, but is not yet supported by a particular JavaScript engine.
133+
*Polyfill* é um termpo para criar um substituto para um método que existe na especificação do JavaScript, mas ainda não tem suporte em alguma engine particular de JavaScript.
135134

136-
We may then implement it manually and populate the built-in prototype with it.
135+
Nesse caso nós podemos implementar e popular o protótipo embutido com ele.
137136

138-
For instance:
137+
Por exemplo:
139138

140139
```js run
141-
if (!String.prototype.repeat) { // if there's no such method
142-
// add it to the prototype
140+
if (!String.prototype.repeat) { // Se não existe esse método
141+
// adiciona no protótipo
143142

144143
String.prototype.repeat = function(n) {
145-
// repeat the string n times
144+
// repete a string n vezes
146145

147-
// actually, the code should be a little bit more complex than that
148-
// (the full algorithm is in the specification)
149-
// but even an imperfect polyfill is often considered good enough
146+
// na realidade, o código deveria ser um pouco mais complexo do que isso
147+
// (o algoritmo completo está na especificação)
148+
// mas mesmo imperfeito, o polyfill é geralmente considerado bom o suficiente
150149
return new Array(n + 1).join(this);
151150
};
152151
}
@@ -155,44 +154,44 @@ alert( "La".repeat(3) ); // LaLaLa
155154
```
156155

157156

158-
## Borrowing from prototypes
157+
## Pegando emprestado dos protótipos
159158

160-
In the chapter <info:call-apply-decorators#method-borrowing> we talked about method borrowing.
159+
No capítulo <info:call-apply-decorators#method-borrowing>, nós falamos sobre pegar métodos emprestado.
161160

162-
That's when we take a method from one object and copy it into another.
161+
Isso é quando nós pegamos um método de um objeto e o copiamos para outro.
163162

164-
Some methods of native prototypes are often borrowed.
163+
Alguns métodos de protótipos nativos são emprestados com muita frequência.
165164

166-
For instance, if we're making an array-like object, we may want to copy some array methods to it.
165+
Por exemplo, se nós estamos fazendo um objeto parecido com um array, nós podemos querer copiar alguns métodos para ele.
167166

168-
E.g.
167+
Veja um exemplo:
169168

170169
```js run
171170
let obj = {
172-
0: "Hello",
173-
1: "world!",
171+
0: "Olá",
172+
1: "mundo!",
174173
length: 2,
175174
};
176175

177176
*!*
178177
obj.join = Array.prototype.join;
179178
*/!*
180179

181-
alert( obj.join(',') ); // Hello,world!
180+
alert( obj.join(',') ); // Olá,mundo!
182181
```
183182

184-
It works because the internal algorithm of the built-in `join` method only cares about the correct indexes and the `length` property. It doesn't check if the object is indeed an array. Many built-in methods are like that.
183+
Ele funciona porque o algoritmo interno do método `join` embutido só precisa dos índices corretos e da propriedade `length`. Ele não confere se o objeto é de fato uma array. Muitos métodos enbutidos são assim.
185184

186-
Another possibility is to inherit by setting `obj.__proto__` to `Array.prototype`, so all `Array` methods are automatically available in `obj`.
185+
Outra possibilidade é herdar configurando `obj.__proto__` para o `Array.prototype`, de forma que todos os métodos de `Array` fiquem automaticamente disponíveis em `obj`.
187186

188-
But that's impossible if `obj` already inherits from another object. Remember, we only can inherit from one object at a time.
187+
Mas isso é impossível se `obj` já herda de outro objeto. Lembre-se, nós só podemos herdar de um objeto por vez.
189188

190-
Borrowing methods is flexible, it allows to mix functionalities from different objects if needed.
189+
Pegar métodos emprestado é mais flexível, isso permite misturar as funcionalidades de diferentes objetos caso necessário.
191190

192-
## Summary
191+
## Resumo
193192

194-
- All built-in objects follow the same pattern:
195-
- The methods are stored in the prototype (`Array.prototype`, `Object.prototype`, `Date.prototype`, etc.)
196-
- The object itself stores only the data (array items, object properties, the date)
197-
- Primitives also store methods in prototypes of wrapper objects: `Number.prototype`, `String.prototype` and `Boolean.prototype`. Only `undefined` and `null` do not have wrapper objects
198-
- Built-in prototypes can be modified or populated with new methods. But it's not recommended to change them. The only allowable case is probably when we add-in a new standard, but it's not yet supported by the JavaScript engine
193+
- Todos os objetos enbutidos seguem o mesmo padrão:
194+
- Os métodos são guardados no protótipo (`Array.prototype`, `Object.prototype`, `Date.prototype`, etc.)
195+
- O objeto só guarda os dados nele mesmo (itens de array, propriedades de objetos, a data)
196+
- Tipos primitivos também guardam métodos em protótipos de objetos que os envolvem (como um invólucro): `Number.prototype`, `String.prototype` e `Boolean.prototype`. Apenas `undefined` e `null` que não tem objetos invólucros.
197+
- Protótipos embutidos podem ser modificados ou populados com novos métodos. Mas modificá-los não é recomendado. O único caso aceitável é provavelmente quando nós adicionamos um novo comportamento e ele ainda não tem suporte em alguma engine JavaScript.

0 commit comments

Comments
 (0)