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"`é amplamente utilizada pelo próprio núcleo do JavaScript. Todas as funções construtoras integradas o utilizam.
4
4
5
-
First we'll look at the details, and then how to use it for adding new capabilities to built-in objects.
5
+
Primeiro veremos os detalhes e depois como usá-lo para adicionar novos recursos a objetos integrados.
6
6
7
7
## Object.prototype
8
8
9
-
Let's say we output an empty object:
9
+
Digamos que produzimos 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]"`? Isto vem de 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
+
... A notação abreviada`obj = {}`é o mesmo que`obj = new Object()`. Onde`Object`é uma função construtora embutida, com o seu próprio `prototype`referenciando um objeto enorme, possuindo`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()`é invocado (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 more `[[Prototype]]`in the chain above`Object.prototype`:
41
+
Observe que não há mais `[[Prototype]]`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`, etc., também tê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`Array.prototype`becomes its prototype and provides methods. That's very memory-efficient.
51
+
Por exemplo, quando criamos um array `[1, 2, 3]`, o construtor padrão `new Array()`é usado internamente. Então`Array.prototype`se torna seu protótipo e fornece métodos. Isso é muito eficiente em termos de memória.
52
52
53
-
By specification, all of the built-in prototypes have `Object.prototype`on the top. That's why some people say that "everything inherits from objects".
53
+
Por especificação, todos os protótipos integrados têm `Object.prototype`no topo. É por isso que algumas pessoas dizem que “tudo herda dos 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 do array é utilizada.
82
82
83
83
84
84

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

90
90
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.
91
+
Outros objetos embutidos também trabalham da mesma forma. Até mesmo funções -- elas são objetos de um construtor`Function`embutido, e os seus métodos (`call`/`apply`, e outros) são obtidos de`Function.prototype`. Funções também têm o seu próprio `toString`.
92
92
93
93
```js run
94
94
functionf() {}
95
95
96
96
alert(f.__proto__==Function.prototype); // true
97
-
alert(f.__proto__.__proto__==Object.prototype); // true, inherit from objects
97
+
alert(f.__proto__.__proto__==Object.prototype); // true, herdado de object
98
98
```
99
99
100
-
## Primitives
100
+
## Primitivos
101
101
102
-
The most intricate thing happens with strings, numbers and booleans.
102
+
As coisas mais complicadas acontecem com strings, números e boleanos.
103
103
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.
104
+
Como sabemos, eles não são objetos. Mas se nós tentarmos acessar as propriedades deles, temporariamente são criados objetos usando os construtores embutidos`String`, `Number` and `Boolean`. Esses objetos fornecem os métodos e desaparecem.
105
105
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`.
106
+
Esses objetos são criados invisivelmente para nós e a maioria dos interpretadores (*engines*) otimizam esse processo, apesar da especificação descrevê-lo exatamente desta forma. Os métodos desses objetos também residem nos protótipos, disponíveis como`String.prototype`, `Number.prototype`e`Boolean.prototype`.
107
107
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.
108
+
```warn header="Os valores `null`e`undefined`não têm objetos que os envolvam"
109
+
O valores especiais `null`e`undefined`se destacam dos outros. Eles não têm 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:
114
+
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
115
116
116
```js run
117
117
String.prototype.show = function() {
118
118
alert(this);
119
119
};
120
120
121
-
"BOOM!".show(); // BOOM!
121
+
"BUM!".show(); // BUM!
122
122
```
123
123
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.
124
+
Durante o processo de desenvolvimento, nós podemos ter novas ideias de métodos embutidos que gostaríamos de ter, e podemos ficar tentados a adicioná-los aos protótipos nativos. Mas isso é geralmente uma má ideia.
125
125
126
126
```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 method of the other.
127
+
Os protótipos são globais, por isso é fácil criar conflitos. Se duas bibliotecas adicionarem um método `String.prototype.show`, então uma delas substituirá o método da outra.
128
128
129
-
So, generally, modifying a native prototype is considered a bad idea.
129
+
Por isso, geralmente, modificar um protótipo nativo é considerado uma má ideia.
130
130
```
131
131
132
-
**In modern programming, there is only one case where modifying native prototypes is approved. That's polyfilling.**
132
+
**Na programação moderna, existe apenas um caso erm que modificar protótipos nativos é aprovado: fazer polyfill (polyfilling).**
133
133
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.
134
+
*Polyfill* é um termo para criar um substituto para um método que existe na especificação, mas que ainda não tem suporte em um particular interpretador de JavaScript.
135
135
136
-
We may then implement it manually and populate the built-in prototype with it.
136
+
Nesse caso nós o podemos implementar e preencher o protótipo embutido com ele.
137
137
138
-
For instance:
138
+
Por exemplo:
139
139
140
140
```js run
141
-
if (!String.prototype.repeat) { //if there's no such method
142
-
//add it to the prototype
141
+
if (!String.prototype.repeat) { //Se não existe esse método
142
+
//adiciona ao protótipo
143
143
144
144
String.prototype.repeat=function(n) {
145
-
//repeat the string n times
145
+
//repete a string n vezes
146
146
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
147
+
//na realidade, o código deveria ser um pouco mais complexo do que isso
148
+
// (o algoritmo completo está na especificação)
149
+
//mas mesmo um polyfill imperfeito, é geralmente considerado bom o suficiente
In the chapter <info:call-apply-decorators#method-borrowing> we talked about method borrowing.
160
+
No capítulo <info:call-apply-decorators#method-borrowing>, nós falamos sobre pegar métodos emprestados.
161
161
162
-
That's when we take a method from one object and copy it into another.
162
+
Isso é quando nós pegamos um método de um objeto e o copiamos para outro.
163
163
164
-
Some methods of native prototypes are often borrowed.
164
+
Alguns métodos de protótipos nativos são emprestados com muita frequência.
165
165
166
-
For instance, if we're making an array-like object, we may want to copy some `Array`methods to it.
166
+
Por exemplo, se estivermos criando um objeto semelhante a um array, podemos querer copiar alguns métodos `Array`para ele.
167
167
168
-
E.g.
168
+
Veja um exemplo:
169
169
170
170
```js run
171
171
let obj = {
172
-
0:"Hello",
173
-
1:"world!",
172
+
0:"Olá",
173
+
1:"mundo!",
174
174
length:2,
175
175
};
176
176
177
177
*!*
178
178
obj.join=Array.prototype.join;
179
179
*/!*
180
180
181
-
alert( obj.join(',') ); //Hello,world!
181
+
alert( obj.join(',') ); //Olá,mundo!
182
182
```
183
183
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.
184
+
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
185
186
-
Another possibility is to inherit by setting `obj.__proto__`to`Array.prototype`, so all `Array`methods are automatically available in`obj`.
186
+
Outra possibilidade é herdando, configurando `obj.__proto__`para`Array.prototype`, de forma que todos os métodos de `Array`fiquem automaticamente disponíveis em`obj`.
187
187
188
-
But that's impossible if `obj`already inherits from another object. Remember, we only can inherit from one object at a time.
188
+
Mas isso é impossível se `obj`já herda de outro objeto. Lembre-se, nós só podemos herdar de um objeto por vez.
189
189
190
-
Borrowing methods is flexible, it allows to mix functionalities from different objects if needed.
190
+
Pegar métodos emprestados é mais flexível, isso permite misturar as funcionalidades de diferentes objetos caso necessário.
191
191
192
-
## Summary
192
+
## Resumo
193
193
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
194
+
-Todos os objetos embutidos seguem o mesmo padrão:
195
+
-Os métodos são guardados no protótipo (`Array.prototype`, `Object.prototype`, `Date.prototype`, etc.)
196
+
-O objeto só guarda os dados nele mesmo (itens de array, propriedades de objetos, uma data)
197
+
-Tipos primitivos também guardam métodos em protótipos de objetos que os envolvem: `Number.prototype`, `String.prototype`e`Boolean.prototype`. Apenas`undefined`e`null`não tem objetos invólucros.
198
+
-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 que ainda não tem suporte em algum interpretador (*engine*) de JavaScript.
0 commit comments