Skip to content

Commit b569358

Browse files
authored
Merge pull request #231 from flaviohblima/develop-function-prototype
F.prototype
2 parents 0b207b5 + 2e32549 commit b569358

File tree

6 files changed

+84
-81
lines changed

6 files changed

+84
-81
lines changed
Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11

2-
Answers:
2+
Respostas:
33

44
1. `true`.
55

6-
The assignment to `Rabbit.prototype` sets up `[[Prototype]]` for new objects, but it does not affect the existing ones.
6+
A atribuição a `Rabbit.prototype` configura o `[[Prototype]]` para novos objetos, mas não afeta os objetos que já existem.
77

88
2. `false`.
99

10-
Objects are assigned by reference. The object from `Rabbit.prototype` is not duplicated, it's still a single object referenced both by `Rabbit.prototype` and by the `[[Prototype]]` of `rabbit`.
10+
Objetos são atribuídos por referência. O objeto do `Rabbit.prototype` não é duplicado, ele continua sendo um único objeto referenciado por `Rabbit.prototype` e pelo `[[Prototype]]` do `rabbit`.
1111

12-
So when we change its content through one reference, it is visible through the other one.
12+
Portanto, quando nós mudamos o seu conteúdo através de uma referência, ele fica visível para as outras.
1313

1414
3. `true`.
1515

16-
All `delete` operations are applied directly to the object. Here `delete rabbit.eats` tries to remove `eats` property from `rabbit`, but it doesn't have it. So the operation won't have any effect.
16+
Todas as operações de `delete` são aplicadas diretamente ao objeto. Neste caso, `delete rabbit.eats` tenta remover a propriedade `eats` do `rabbit`, mas ele não a tem. Assim, essa operação não tem nenhum efeito.
1717

1818
4. `undefined`.
1919

20-
The property `eats` is deleted from the prototype, it doesn't exist any more.
20+
A propriedade `eats` é deletada do protótipo, então ela realmente não existe mais.

1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md

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

33
---
44

5-
# Changing "prototype"
5+
# Mudando o "prototype"
66

7-
In the code below we create `new Rabbit`, and then try to modify its prototype.
7+
No código abaixo, nós criamos um `new Rabbit`, depois tentamos modificar seu protótipo.
88

9-
In the start, we have this code:
9+
No começo, nós temos esse código:
1010

1111
```js run
1212
function Rabbit() {}
@@ -19,8 +19,7 @@ let rabbit = new Rabbit();
1919
alert( rabbit.eats ); // true
2020
```
2121

22-
23-
1. We added one more string (emphasized). What will `alert` show now?
22+
1. Nós adicionamos uma linha (realçada). O que o `alert` vai mostrar agora?
2423

2524
```js
2625
function Rabbit() {}
@@ -37,7 +36,7 @@ alert( rabbit.eats ); // true
3736
alert( rabbit.eats ); // ?
3837
```
3938

40-
2. ...And if the code is like this (replaced one line)?
39+
2. ...E se o código for assim (a linha foi substituída)?
4140

4241
```js
4342
function Rabbit() {}
@@ -54,7 +53,7 @@ alert( rabbit.eats ); // true
5453
alert( rabbit.eats ); // ?
5554
```
5655

57-
3. And like this (replaced one line)?
56+
3. E se for assim (a linha foi substituída)?
5857

5958
```js
6059
function Rabbit() {}
@@ -71,7 +70,7 @@ alert( rabbit.eats ); // true
7170
alert( rabbit.eats ); // ?
7271
```
7372

74-
4. The last variant:
73+
4. A última variação:
7574

7675
```js
7776
function Rabbit() {}
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
We can use such approach if we are sure that `"constructor"` property has the correct value.
1+
Nós podemos usar essa abordagem se nós tivermos a certeza de que a propriedade `"constructor"` tem o valor correto.
22

3-
For instance, if we don't touch the default `"prototype"`, then this code works for sure:
3+
Por exemplo, se nós não tocarmos no `"prototype"` padrão, então esse código funciona com certeza:
44

55
```js run
66
function User(name) {
@@ -10,14 +10,14 @@ function User(name) {
1010
let user = new User('John');
1111
let user2 = new user.constructor('Pete');
1212

13-
alert( user2.name ); // Pete (worked!)
13+
alert( user2.name ); // Pete (funcionou!)
1414
```
1515

16-
It worked, because `User.prototype.constructor == User`.
16+
Funcionou, porque `User.prototype.constructor == User`.
1717

18-
..But if someone, so to speak, overwrites `User.prototype` and forgets to recreate `constructor` to reference `User`, then it would fail.
18+
...Mas se alguém, por acaso, sobrescrever `User.prototype` e se esquecer de recriar o `constructor` referenciando `User`, então o código irá falhar.
1919

20-
For instance:
20+
Por exemplo:
2121

2222
```js run
2323
function User(name) {
@@ -33,17 +33,17 @@ let user2 = new user.constructor('Pete');
3333
alert( user2.name ); // undefined
3434
```
3535

36-
Why `user2.name` is `undefined`?
36+
Por que `user2.name` está `undefined`?
3737

38-
Here's how `new user.constructor('Pete')` works:
38+
Abaixo está como o `new user.constructor('Pete')` funciona:
3939

40-
1. First, it looks for `constructor` in `user`. Nothing.
41-
2. Then it follows the prototype chain. The prototype of `user` is `User.prototype`, and it also has no `constructor` (because we "forgot" to set it right!).
42-
3. Going further up the chain, `User.prototype` is a plain object, its prototype is the built-in `Object.prototype`.
43-
4. Finally, for the built-in `Object.prototype`, there's a built-in `Object.prototype.constructor == Object`. So it is used.
40+
1. Primeiro, ele procura o `constructor` do `user`. Não o encontra.
41+
2. Depois, ele segue a cadeia de protótipos. O protótipo de `user` é `User.prototype`, e ele também não tem um `constructor` (porque nós nos "esquecemos" de configurá-lo!).
42+
3. Indo adiante na cadeia, `User.prototype` é um objeto vazio, cujo protótipo é o `Object.prototype` padrão.
43+
4. Por último, para o `Object.prototype` padrão existe um `Object.prototype.constructor == Object` padrão. Então, ele é usado.
4444

45-
Finally, at the end, we have `let user2 = new Object('Pete')`.
45+
No fim, nós temos `let user2 = new Object('Pete')`.
4646

47-
Probably, that's not what we want. We'd like to create `new User`, not `new Object`. That's the outcome of the missing `constructor`.
47+
Provavelmente não é isso que nós queremos. Nós gostaríamos de criar um `new User`, não um `new Object`. Essa é a consequência da falta de um `constructor`.
4848

49-
(Just in case you're curious, the `new Object(...)` call converts its argument to an object. That's a theoretical thing, in practice no one calls `new Object` with a value, and generally we don't use `new Object` to make objects at all).
49+
(Caso você esteja curioso, a chamada `new Object(...)` converte o seu argumento para um objeto. Isso é algo teórico, mas, na prática, ninguém faz a chamada `new Object` com um valor, e geralmente nós não usamos `new Object` para criar objetos).

1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md

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

33
---
44

5-
# Create an object with the same constructor
5+
# Criando um objeto com o mesmo construtor
66

7-
Imagine, we have an arbitrary object `obj`, created by a constructor function -- we don't know which one, but we'd like to create a new object using it.
7+
Imagine que nós temos um objeto `obj` arbitrário, criado por uma função construtura -- nós não sabemos qual é, mas nós gostaríamos de criar um objeto novo usando ela.
88

9-
Can we do it like that?
9+
Nós podemos fazer isso dessa forma?
1010

1111
```js
1212
let obj2 = new obj.constructor();
1313
```
1414

15-
Give an example of a constructor function for `obj` which lets such code work right. And an example that makes it work wrong.
15+
Dê um exemplo de uma função construtora para o `obj` que faça esse código funcionar corretamente, e outro exemplo que faça ele não funcionar.
Lines changed: 48 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
# F.prototype
22

3-
Remember, new objects can be created with a constructor function, like `new F()`.
3+
Lembre-se, novos objetos podem ser criados com uma função construtora, usando `new F()`.
44

5-
If `F.prototype` is an object, then the `new` operator uses it to set `[[Prototype]]` for the new object.
5+
Se `F.prototype` for um objeto, então o operador `new` usa ela para configurar o `[[Prototype]]` do novo objeto.
66

77
```smart
8-
JavaScript had prototypal inheritance from the beginning. It was one of the core features of the language.
8+
JavaScript tem herança prototipada desde o começo. Isso era uma das funcionalidades centrais da linguagem.
99
10-
But in the old times, there was no direct access to it. The only thing that worked reliably was a `"prototype"` property of the constructor function, described in this chapter. So there are many scripts that still use it.
10+
Mas antigamente não havia um acesso direto a ela. A única coisa que funcionava de forma confiável era uma propriedade `"prototype"` da função construtora, descrita nesse capítulo. Então, existem muitos scripts que ainda a utilizam.
1111
```
1212

13-
Please note that `F.prototype` here means a regular property named `"prototype"` on `F`. It sounds something similar to the term "prototype", but here we really mean a regular property with this name.
13+
Note que o `F.prototype` aqui significa uma propriedade regular chamada `"prototype"` dentro de `F`. Isso soa um pouco similar ao termo "prototype" (protótipo), mas aqui nós estamos falando realmente de uma propriedade regular com esse nome.
1414

15-
Here's the example:
15+
Aqui temos um exemplo:
1616

1717
```js run
1818
let animal = {
@@ -27,32 +27,32 @@ function Rabbit(name) {
2727
Rabbit.prototype = animal;
2828
*/!*
2929

30-
let rabbit = new Rabbit("White Rabbit"); // rabbit.__proto__ == animal
30+
let rabbit = new Rabbit("Coelho Branco"); // rabbit.__proto__ == animal
3131

3232
alert( rabbit.eats ); // true
3333
```
3434

35-
Setting `Rabbit.prototype = animal` literally states the following: "When a `new Rabbit` is created, assign its `[[Prototype]]` to `animal`".
35+
Configurando `Rabbit.prototype = animal` literalmente significa o seguinte: "Quando o `new Rabbit` for criado, atribua seu `[[Prototype]]` para `animal`".
3636

37-
That's the resulting picture:
37+
Essa é a imagem do resultado:
3838

3939
![](proto-constructor-animal-rabbit.svg)
4040

41-
On the picture, `"prototype"` is a horizontal arrow, meaning a regular property, and `[[Prototype]]` is vertical, meaning the inheritance of `rabbit` from `animal`.
41+
Na imagem, `"prototype"` é a seta na horizontal, indicando uma propriedade regular, e `[[Prototype]]` está na vertical, indicando a herança de `rabbit` vinda de `animal`.
4242

43-
```smart header="`F.prototype` only used at `new F` time"
44-
`F.prototype` property is only used when `new F` is called, it assigns `[[Prototype]]` of the new object.
43+
```smart header="`F.prototype` é usada apenas na chamada `new F`"
44+
A propriedade `F.prototype` é usada apenas quando `new F` é chamado, e ela atribui um valor para o `[[Prototype]]` do novo objeto.
4545

46-
If, after the creation, `F.prototype` property changes (`F.prototype = <another object>`), then new objects created by `new F` will have another object as `[[Prototype]]`, but already existing objects keep the old one.
46+
Se, depois da criação, a propriedade `F.prototype` mudar (`F.prototype = <another object>`), então novos objetos criados com `new F` vão ter outro objeto como `[[Prototype]]`, enquanto os objetos que já existirem vão manter o antigo.
4747
```
4848
49-
## Default F.prototype, constructor property
49+
## F.prototype padrão, propriedade do construtor
5050
51-
Every function has the `"prototype"` property even if we don't supply it.
51+
Toda função tem a propriedade `"prototype"`, mesmo quando nós não a provermos.
5252
53-
The default `"prototype"` is an object with the only property `constructor` that points back to the function itself.
53+
O `"prototype"` padrão é um objeto com apenas uma propriedade `constructor` que aponta para a própria função a que pertence.
5454
55-
Like this:
55+
Assim:
5656
5757
```js
5858
function Rabbit() {}
@@ -64,58 +64,58 @@ Rabbit.prototype = { constructor: Rabbit };
6464

6565
![](function-prototype-constructor.svg)
6666

67-
We can check it:
67+
Nós podemos conferir isso:
6868

6969
```js run
7070
function Rabbit() {}
71-
// by default:
71+
// Por definição:
7272
// Rabbit.prototype = { constructor: Rabbit }
7373

7474
alert( Rabbit.prototype.constructor == Rabbit ); // true
7575
```
7676

77-
Naturally, if we do nothing, the `constructor` property is available to all rabbits through `[[Prototype]]`:
77+
Naturalmente, se nós não fizermos nada, a propriedade `constructor` está disponível para todos os coelhos (*rabbits*) através do `[[Prototype]]`:
7878

7979
```js run
8080
function Rabbit() {}
81-
// by default:
81+
// Por definição:
8282
// Rabbit.prototype = { constructor: Rabbit }
8383

84-
let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}
84+
let rabbit = new Rabbit(); // herda de {constructor: Rabbit}
8585

86-
alert(rabbit.constructor == Rabbit); // true (from prototype)
86+
alert(rabbit.constructor == Rabbit); // true (vindo do protótipo)
8787
```
8888

8989
![](rabbit-prototype-constructor.svg)
9090

91-
We can use `constructor` property to create a new object using the same constructor as the existing one.
91+
Nós podemos usar a propriedade `constructor` para criar um objeto novo usando o próprio construtor de um objeto que já exista.
9292

93-
Like here:
93+
Como abaixo:
9494

9595
```js run
9696
function Rabbit(name) {
9797
this.name = name;
9898
alert(name);
9999
}
100100

101-
let rabbit = new Rabbit("White Rabbit");
101+
let rabbit = new Rabbit("Coelho Branco");
102102

103103
*!*
104-
let rabbit2 = new rabbit.constructor("Black Rabbit");
104+
let rabbit2 = new rabbit.constructor("Coelho Preto");
105105
*/!*
106106
```
107107

108-
That's handy when we have an object, don't know which constructor was used for it (e.g. it comes from a 3rd party library), and we need to create another one of the same kind.
108+
Isso é prático quando nós temos um objeto, não sabemos que construtor foi usado para ele (de uma biblioteca de terceiros, por exemplo), e nós precisamos de criar outro objeto do mesmo tipo.
109109

110-
But probably the most important thing about `"constructor"` is that...
110+
Mas provavelmente a coisa mais importante sobre o `"constructor"` é que...
111111

112-
**...JavaScript itself does not ensure the right `"constructor"` value.**
112+
**...O próprio JavaScript não garante qual é o valor correto do `"constructor"`.**
113113

114-
Yes, it exists in the default `"prototype"` for functions, but that's all. What happens with it later -- is totally on us.
114+
Sim, existe um `"prototype"` padrão para funções, mas é só isso. O que acontece com ele depois -- está totalmente por nossa conta.
115115

116-
In particular, if we replace the default prototype as a whole, then there will be no `"constructor"` in it.
116+
Em particular, se nós substituirmos o `prototype` padrão, não vai haver um `"constructor"` nele.
117117

118-
For instance:
118+
Por exemplo:
119119

120120
```js run
121121
function Rabbit() {}
@@ -129,18 +129,18 @@ alert(rabbit.constructor === Rabbit); // false
129129
*/!*
130130
```
131131

132-
So, to keep the right `"constructor"` we can choose to add/remove properties to the default `"prototype"` instead of overwriting it as a whole:
132+
Portanto, para manter o `"constructor"` certo, nós podemos escolher adicionar/remover propriedades do `"prototype"` ao invés de sobrescrevê-lo completamente:
133133

134134
```js
135135
function Rabbit() {}
136136

137-
// Not overwrite Rabbit.prototype totally
138-
// just add to it
137+
// não sobrescreva Rabbit.prototype completamente
138+
// apenas adicione
139139
Rabbit.prototype.jumps = true
140-
// the default Rabbit.prototype.constructor is preserved
140+
// o Rabbit.prototype.constructor padrão fica preservado
141141
```
142142

143-
Or, alternatively, recreate the `constructor` property manually:
143+
Outra alternativa é recriar a propriedade `constructor` manualmente:
144144

145145
```js
146146
Rabbit.prototype = {
@@ -150,26 +150,26 @@ Rabbit.prototype = {
150150
*/!*
151151
};
152152

153-
// now constructor is also correct, because we added it
153+
// agora o constructor também está correto, porque nós o adicionamos
154154
```
155155

156+
## Resumo
156157

157-
## Summary
158+
Neste capítulo, nós descrevemos brevemente a forma de configurar um `[[Prototype]]` para os objetos criados via função construtura. Mais tarde nós vamos ver padrões (*patterns*) mais avançados de programação que dependem disso.
158159

159-
In this chapter we briefly described the way of setting a `[[Prototype]]` for objects created via a constructor function. Later we'll see more advanced programming patterns that rely on it.
160+
É tudo bem simples, mas aqui estão algumas notas para deixar as coisas claras:
160161

161-
Everything is quite simple, just a few notes to make things clear:
162+
- A propriedade `F.prototype` (não confunda com o `[[Prototype]]`) configura o `[[Prototype]]` de novos objetos quando `new F()` é chamado.
163+
- O valor de `F.prototype` deveria ser um objeto ou `null`: outros valores não vão funcionar.
164+
- A propriedade `"prototype"` só tem o efeito especial quando configurada em uma função construtora, e invocada com `new`.
162165

163-
- The `F.prototype` property (don't mistake it for `[[Prototype]]`) sets `[[Prototype]]` of new objects when `new F()` is called.
164-
- The value of `F.prototype` should be either an object or `null`: other values won't work.
165-
- The `"prototype"` property only has such a special effect when set on a constructor function, and invoked with `new`.
166+
Em objetos regulares, o `prototype` não tem nada de especial:
166167

167-
On regular objects the `prototype` is nothing special:
168168
```js
169169
let user = {
170170
name: "John",
171-
prototype: "Bla-bla" // no magic at all
171+
prototype: "Bla-bla" // nenhuma mágica aqui
172172
};
173173
```
174174
175-
By default all functions have `F.prototype = { constructor: F }`, so we can get the constructor of an object by accessing its `"constructor"` property.
175+
Por padrão, todas as funções possuem `F.prototype = { constructor: F }`, então nós podemos obter o construtor de um objeto acessando sua propriedade `"constructor"`.

images.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
proto-constructor-animal-rabbit.svg:
2+
White Rabbit:
3+
text: Coelho Branco
4+
position: center

0 commit comments

Comments
 (0)