Skip to content

Commit 82c559c

Browse files
committed
Translate constructor chapter of object basics
1 parent 5e403a0 commit 82c559c

File tree

6 files changed

+99
-101
lines changed

6 files changed

+99
-101
lines changed

1-js/04-object-basics/06-constructor-new/1-two-functions-one-object/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
Yes, it's possible.
1+
Sim, é possível.
22

3-
If a function returns an object then `new` returns it instead of `this`.
3+
Se uma função retorna um objeto, então `new` o retorna ao invés de `this`.
44

5-
So they can, for instance, return the same externally defined object `obj`:
5+
Então elas podem, por exemplo, retornar o mesmo objeto `obj` definido externamente:
66

77
```js run no-beautify
88
let obj = {};

1-js/04-object-basics/06-constructor-new/1-two-functions-one-object/task.md

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

33
---
44

5-
# Two functionsone object
5+
# Duas funçõesum objeto
66

7-
Is it possible to create functions `A` and `B` so that `new A() == new B()`?
7+
É possível criar funções `A` e `B` tais que `new A()==new B()`?
88

99
```js no-beautify
1010
function A() { ... }
@@ -16,4 +16,4 @@ let b = new B();
1616
alert( a == b ); // true
1717
```
1818

19-
If it is, then provide an example of their code.
19+
Se sim, então forneça um exemplo de seus códigos.

1-js/04-object-basics/06-constructor-new/2-calculator-constructor/task.md

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

33
---
44

5-
# Create new Calculator
5+
# Crie new Calculator
66

7-
Create a constructor function `Calculator` that creates objects with 3 methods:
7+
Crie uma função construtora `Calculator` que crie objetos com 3 métodos:
88

9-
- `read()` prompts for two values and saves them as object properties with names `a` and `b` respectively.
10-
- `sum()` returns the sum of these properties.
11-
- `mul()` returns the multiplication product of these properties.
9+
- `read()` solicita 2 valores e os guarda como propriedades do objeto com nomes `a` e `b` respectivamente.
10+
- `sum()` retorna a soma dessas propriedades.
11+
- `mul()` retorna o produto da multiplicação dessas propriedades.
1212

13-
For instance:
13+
Por exemplo:
1414

1515
```js
1616
let calculator = new Calculator();

1-js/04-object-basics/06-constructor-new/3-accumulator/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
```js run demo
44
function Accumulator(startingValue) {
55
this.value = startingValue;
6-
6+
77
this.read = function() {
8-
this.value += +prompt('How much to add?', 0);
8+
this.value += +prompt('Quanto quer adicionar?', 0);
99
};
1010

1111
}

1-js/04-object-basics/06-constructor-new/3-accumulator/task.md

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

33
---
44

5-
# Create new Accumulator
5+
# Crie new Accumulator
66

7-
Create a constructor function `Accumulator(startingValue)`.
7+
Crie uma função construtora `Accumulator(startingValue)`.
88

9-
Object that it creates should:
9+
O objeto que ela cria deve:
1010

11-
- Store the "current value" in the property `value`. The starting value is set to the argument of the constructor `startingValue`.
12-
- The `read()` method should use `prompt` to read a new number and add it to `value`.
11+
- Armazenar o "valor atual" na propriedade `value`. O valor inicial é definido no argumento do construtor `startingValue` .
12+
- O método `read()` deve usar `prompt` para ler um novo número e adicioná-lo ao `value`.
1313

14-
In other words, the `value` property is the sum of all user-entered values with the initial value `startingValue`.
14+
Em outras palavras, a propriedade `value` é a soma de todos os valores digitados pelo usuário com o valor inicial `startingValue`.
1515

16-
Here's the demo of the code:
16+
Aqui está uma demonstração do código:
1717

1818
```js
19-
let accumulator = new Accumulator(1); // initial value 1
19+
let accumulator = new Accumulator(1); // valor inicial 1
2020

21-
accumulator.read(); // adds the user-entered value
22-
accumulator.read(); // adds the user-entered value
21+
accumulator.read(); // adiciona o valor digitado pelo usuário
22+
accumulator.read(); // adiciona o valor digitado pelo usuário
2323

24-
alert(accumulator.value); // shows the sum of these values
24+
alert(accumulator.value); // apresenta a soma destes valores
2525
```
2626

2727
[demo]
Lines changed: 74 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
# Constructor, operator "new"
1+
# Construtor, operador "new"
22

3-
The regular `{...}` syntax allows us to create one object. But often we need to create many similar objects, like multiple users or menu items and so on.
3+
A sintaxe regular `{...}` permite criar um objeto. Mas frequentemente precisamos de criar vários objetos iguais, como diversos usuários, itens de um menu, etc.
44

5-
That can be done using constructor functions and the `"new"` operator.
5+
Isto pode ser feito usando as funções construtoras e o operador `"new"` .
66

7-
## Constructor function
7+
## Funções construtoras
88

9-
Constructor functions technically are regular functions. There are two conventions though:
9+
Funções construtoras são tecnicamente, funções regulares. Entretanto, existem duas convenções:
1010

11-
1. They are named with capital letter first.
12-
2. They should be executed only with `"new"` operator.
11+
1. Elas são nomeadas com a primeira letra em maiúsculas.
12+
2. Elas devem ser executadas apenas através do operador `"new"`.
1313

14-
For instance:
14+
Por exemplo:
1515

1616
```js run
1717
function User(name) {
@@ -27,182 +27,180 @@ alert(user.name); // Jack
2727
alert(user.isAdmin); // false
2828
```
2929

30-
When a function is executed with `new`, it does the following steps:
30+
Quando uma função é executada através de `new`, ela segue os seguintes passos:
3131

32-
1. A new empty object is created and assigned to `this`.
33-
2. The function body executes. Usually it modifies `this`, adds new properties to it.
34-
3. The value of `this` is returned.
32+
1. Um novo objeto é criado e atribuído ao `this`.
33+
2. O corpo da função é executado. Normalmente, ele modifica o `this`, adicionando novas propriedades.
34+
3. O valor de `this` é retornado.
3535

36-
In other words, `new User(...)` does something like:
36+
Em outras palavras, `new User(...)` faz algo parecido com:
3737

3838
```js
3939
function User(name) {
4040
*!*
41-
// this = {}; (implicitly)
41+
// this = {}; (implicitamente)
4242
*/!*
4343

44-
// add properties to this
44+
// adiciona propriedades ao this
4545
this.name = name;
4646
this.isAdmin = false;
4747

4848
*!*
49-
// return this; (implicitly)
49+
// return this; (implicitamente)
5050
*/!*
5151
}
5252
```
5353

54-
So `let user = new User("Jack")` gives the same result as:
54+
Então, `let user = new User("Jack")` resulta no mesmo que:
5555

5656
```js
5757
let user = {
5858
name: "Jack",
59-
isAdmin: false
59+
isAdmin: false (falso)
6060
};
6161
```
6262

63-
Now if we want to create other users, we can call `new User("Ann")`, `new User("Alice")` and so on. Much shorter than using literals every time, and also easy to read.
63+
Agora se queremos criar outros usuários, podemos chamar `new User("Ann")`, `new User("Alice")` e assim por diante. Muito mais curto do que usar objetos literais toda vez, e também mais fácil de ler.
6464

65-
That's the main purpose of constructors -- to implement reusable object creation code.
65+
Este é o principal propósito dos construtores -- implementar códigos de criação de objetos reutilizáveis.
6666

67-
Let's note once again -- technically, any function (except arrow functions, as they don't have `this`) can be used as a constructor. It can be run with `new`, and it will execute the algorithm above. The "capital letter first" is a common agreement, to make it clear that a function is to be run with `new`.
67+
Note mais uma vez -- tecnicamente, qualquer função (com exceção das arrow functions, já que elas não possuem o `this`) pode ser usada como um construtor. Pode ser chamada com `new`, e irá executar o algoritmo acima. A "primeira letra maiúscula" é um acordo comum, para deixar claro que uma função é para ser executada com `new`.
6868

6969
````smart header="new function() { ... }"
70-
If we have many lines of code all about creation of a single complex object, we can wrap them in an immediately called constructor function, like this:
70+
Se tivermos várias linhas de código voltadas para a criação de um único objeto complexo, nós podemos embrulhá-las em uma função construtora, como:
7171
7272
```js
73-
// create a function and immediately call it with new
74-
let user = new function() {
73+
// cria uma função e imediatamente a chama com new
74+
let user = new function() {
7575
this.name = "John";
7676
this.isAdmin = false;
7777
78-
// ...other code for user creation
79-
// maybe complex logic and statements
80-
// local variables etc
78+
// ...outro código para criação de usuário
79+
// possivelmente lógica complexa e declarações
80+
// variáveis locais etc
8181
};
8282
```
83-
84-
This constructor can't be called again, because it is not saved anywhere, just created and called. So this trick aims to encapsulate the code that constructs the single object, without future reuse.
83+
Esse construtor não pode ser chamado novamente porque ele não está salvo em nenhum lugar, apenas foi criado e chamado. Então, esse truque visa encapsular o código que constrói o único objeto, sem reutilização futura.
8584
````
8685

87-
## Constructor mode test: new.target
86+
## Teste para o modo construtor: new.target
8887

89-
```smart header="Advanced stuff"
90-
The syntax from this section is rarely used, skip it unless you want to know everything.
88+
```smart header="Material avançado"
89+
A sintaxe desta seção é raramente usada, pule a menos que você queira saber sobre tudo.
9190
```
9291

93-
Inside a function, we can check whether it was called with `new` or without it, using a special `new.target` property.
94-
95-
It is undefined for regular calls and equals the function if called with `new`:
92+
Dentro de uma função, nós podemos checar se ela foi chamada com `new` ou sem ele, usando a propriedade especial `new.target`.
9693

94+
Ela é vazia para chamadas regulares e igual à função se esta foi chamada com ``new`:
9795
```js run
9896
function User() {
9997
alert(new.target);
10098
}
10199

102-
// without "new":
100+
// sem "new":
103101
*!*
104102
User(); // undefined
105103
*/!*
106104

107-
// with "new":
105+
// com "new":
108106
*!*
109107
new User(); // function User { ... }
110108
*/!*
111109
```
112110

113-
That can be used inside the function to know whether it was called with `new`, "in constructor mode", or without it, "in regular mode".
111+
Isto pode ser usado dentro da função para saber se ela foi chamada através do `new`, "em modo construtor", ou sem ele, "em modo comum" .
114112

115-
We can also make both `new` and regular calls to do the same, like this:
113+
Nós também podemos fazer com que ambos, `new` e chamadas comuns, se comportem da mesma maneira, assim:
116114

117115
```js run
118116
function User(name) {
119-
if (!new.target) { // if you run me without new
120-
return new User(name); // ...I will add new for you
117+
if (!new.target) { // se você me executar sem new
118+
return new User(name); // ...eu irei adicioná-lo para você
121119
}
122120

123121
this.name = name;
124122
}
125123

126-
let john = User("John"); // redirects call to new User
124+
let john = User("John"); // redireciona a chamada para new User
127125
alert(john.name); // John
128126
```
129127

130-
This approach is sometimes used in libraries to make the syntax more flexible. So that people may call the function with or without `new`, and it still works.
128+
Essa abordagem é utilizada algumas vezes em bibliotecas para deixar a sintaxe mais flexível. Para que as pessoas possam chamar as funções com ou sem `new`, e ela ainda sim, funcionará.
131129

132-
Probably not a good thing to use everywhere though, because omitting `new` makes it a bit less obvious what's going on. With `new` we all know that the new object is being created.
130+
Porém, provavelmente não é boa para usar em qualquer lugar, pois omitir `new` faz ficar um pouco menos óbvio o que está acontecendo. Com `new` todos sabemos que o novo objeto está sendo criado.
133131

134-
## Return from constructors
132+
## Return dentro de construtores
135133

136-
Usually, constructors do not have a `return` statement. Their task is to write all necessary stuff into `this`, and it automatically becomes the result.
134+
Geralmente, construtores não têm uma declaração `return`. A tarefa deles é escrever todas as coisas dentro do `this`, e ele automaticamente se torna no resultado.
137135

138-
But if there is a `return` statement, then the rule is simple:
136+
Mas se existir uma declaração `return`, então a regra é simples:
139137

140-
- If `return` is called with an object, then the object is returned instead of `this`.
141-
- If `return` is called with a primitive, it's ignored.
138+
- Se `return` é chamado com um objeto, então ele é retornado ao invés de `this`.
139+
- Se `return` é chamado com um primitivo, ele é ignorado.
142140

143-
In other words, `return` with an object returns that object, in all other cases `this` is returned.
141+
Em outras palavras, `return` com um objeto retorna o objeto, em todos os outros casos, o `this` é retornado.
144142

145-
For instance, here `return` overrides `this` by returning an object:
143+
Por exemplo, aqui, `return` sobrepõe o `this` retornando um objeto:
146144

147145
```js run
148146
function BigUser() {
149147

150148
this.name = "John";
151149

152-
return { name: "Godzilla" }; // <-- returns this object
150+
return { name: "Godzilla" }; // <-- retorna esse objeto
153151
}
154152

155-
alert( new BigUser().name ); // Godzilla, got that object
153+
alert( new BigUser().name ); // Godzilla, pegou aquele objeto
156154
```
157155

158-
And here's an example with an empty `return` (or we could place a primitive after it, doesn't matter):
156+
E aqui está um exemplo com um `return` vazio (ou poderíamos colocar um primitivo depois dele, não importa):
159157

160158
```js run
161159
function SmallUser() {
162160

163161
this.name = "John";
164162

165-
return; // <-- returns this
163+
return; // <-- retorna this
166164
}
167165

168166
alert( new SmallUser().name ); // John
169167
```
170168

171-
Usually constructors don't have a `return` statement. Here we mention the special behavior with returning objects mainly for the sake of completeness.
169+
Geralmente os construtores não têm uma declaração `return`. Aqui, nós mencionamos o comportamento especial com objetos retornados principalmente por uma questão de integralidade.
172170

173-
````smart header="Omitting parentheses"
174-
By the way, we can omit parentheses after `new`:
171+
````smart header="Omitindo parênteses"
172+
A propósito, nós podemos omitir os parênteses depois de `new`:
175173
176174
```js
177-
let user = new User; // <-- no parentheses
178-
// same as
175+
let user = new User; // <-- sem parênteses
176+
// igual a
179177
let user = new User();
180178
```
181179
182-
Omitting parentheses here is not considered a "good style", but the syntax is permitted by specification.
180+
Omitir os parênteses aqui não é considerada uma boa prática, mas a sintaxe é permitida pela especificação.
183181
````
184182

185-
## Methods in constructor
183+
## Métodos no construtor
186184

187-
Using constructor functions to create objects gives a great deal of flexibility. The constructor function may have parameters that define how to construct the object, and what to put in it.
185+
Usar funções construtoras para criar objetos nos dá bastante flexibilidade. A função construtora pode ter parâmetros que definam como construir o objeto, e o que colocar dentro dele.
188186

189-
Of course, we can add to `this` not only properties, but methods as well.
187+
Claro, nós podemos adicionar ao `this` não apenas propriedades, mas métodos também.
190188

191-
For instance, `new User(name)` below creates an object with the given `name` and the method `sayHi`:
189+
Por exemplo, `new User(name)` abaixo, cria um objeto com o dado `name` e o método `sayHi`:
192190

193191
```js run
194192
function User(name) {
195193
this.name = name;
196194

197195
this.sayHi = function() {
198-
alert( "My name is: " + this.name );
196+
alert( "Meu nome é: " + this.name );
199197
};
200198
}
201199

202200
*!*
203201
let john = new User("John");
204202

205-
john.sayHi(); // My name is: John
203+
john.sayHi(); // Meu nome é: John
206204
*/!*
207205

208206
/*
@@ -213,19 +211,19 @@ john = {
213211
*/
214212
```
215213

216-
To create complex objects, there's a more advanced syntax, [classes](info:classes), that we'll cover later.
214+
Para criar objetos complexos, existe uma sintaxe mais avançada, [classes](info:classes), que nós iremos abordar mais para frente.
217215

218-
## Summary
216+
## Sumário
219217

220-
- Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first.
221-
- Constructor functions should only be called using `new`. Such a call implies a creation of empty `this` at the start and returning the populated one at the end.
218+
- Funções construtoras ou, resumidamente, construtores, são funções comuns, mas existe um acordo comum para nomeá-las com a primeira letra em maiúsculas.
219+
- Funções construtoras deveriam ser chamadas apenas usando `new`. Tal chamada implica a criação de um `this` vazio no começo e o retornando completo ao final.
222220

223-
We can use constructor functions to make multiple similar objects.
221+
Nós podemos usar funções construtoras para fazer diversos objetos iguais.
224222

225-
JavaScript provides constructor functions for many built-in language objects: like `Date` for dates, `Set` for sets and others that we plan to study.
223+
JavaScript fornece funções construtoras para muitos objetos internos da linguagem: como `Date` para datas, `Set` para conjuntos e outros que nós planejamos estudar.
226224

227-
```smart header="Objects, we'll be back!"
228-
In this chapter we only cover the basics about objects and constructors. They are essential for learning more about data types and functions in the next chapters.
225+
```smart header="Objetos, nós voltaremos!"
226+
Nesse capítulo nós cobrimos apenas o básico sobre objetos e construtores. Eles são essenciais para aprender mais sobre tipos de dados e funções nos próximos capítulos.
229227
230-
After we learn that, we return to objects and cover them in-depth in the chapters <info:prototypes> and <info:classes>.
228+
Depois que aprendermos isso, nós voltamos para os objetos e os cobrimos a fundo nos capítulos <info:prototypes> e <info:classes>.
231229
```

0 commit comments

Comments
 (0)