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
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.
4
4
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.
6
6
7
7
## Object.prototype
8
8
9
-
Let's say we output an empty object:
9
+
Digamos que a gente imprima um objeto vazio:
10
10
11
11
```js run
12
12
let obj = {};
13
13
alert( obj ); // "[object Object]" ?
14
14
```
15
15
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!
17
17
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.
19
19
20
-
Here's what's going on:
20
+
Veja o que está acontecendo:
21
21
22
22

23
23
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:
25
25
26
26

27
27
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`.
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`:
42
42
43
43
```js run
44
44
alert(Object.prototype.__proto__); // null
45
45
```
46
46
47
-
## Other built-in prototypes
47
+
## Outros protótipos embutidos
48
48
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.
50
50
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.
52
52
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".
54
54
55
-
Here's the overall picture (for 3 built-ins to fit):
55
+
Aqui temos uma visão geral (para 3 protótipos embutidos):
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:
75
75
76
76
```js run
77
77
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
79
79
```
80
80
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.
82
82
83
83
84
84

85
85
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`):
88
87
89
88

90
89
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`.
92
91
93
92
```js run
94
93
functionf() {}
95
94
96
95
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
98
97
```
99
98
100
-
## Primitives
99
+
## Primitivos
101
100
102
-
The most intricate thing happens with strings, numbers and booleans.
101
+
As coisas mais complicadas acontecem com strings, números e boleanos.
103
102
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.
105
104
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`.
107
106
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.
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:
115
114
116
115
```js run
117
116
String.prototype.show = function() {
118
117
alert(this);
119
118
};
120
119
121
-
"BOOM!".show(); // BOOM!
120
+
"BUM!".show(); // BUM!
122
121
```
123
122
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.
125
124
126
125
```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.
128
127
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.
130
129
```
131
130
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).**
133
132
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.
135
134
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.
137
136
138
-
For instance:
137
+
Por exemplo:
139
138
140
139
```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
143
142
144
143
String.prototype.repeat=function(n) {
145
-
//repeat the string n times
144
+
//repete a string n vezes
146
145
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
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.
161
160
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.
163
162
164
-
Some methods of native prototypes are often borrowed.
163
+
Alguns métodos de protótipos nativos são emprestados com muita frequência.
165
164
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.
167
166
168
-
E.g.
167
+
Veja um exemplo:
169
168
170
169
```js run
171
170
let obj = {
172
-
0:"Hello",
173
-
1:"world!",
171
+
0:"Olá",
172
+
1:"mundo!",
174
173
length:2,
175
174
};
176
175
177
176
*!*
178
177
obj.join=Array.prototype.join;
179
178
*/!*
180
179
181
-
alert( obj.join(',') ); //Hello,world!
180
+
alert( obj.join(',') ); //Olá,mundo!
182
181
```
183
182
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.
185
184
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`.
187
186
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.
189
188
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.
191
190
192
-
## Summary
191
+
## Resumo
193
192
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