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 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.
4
4
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"` .
6
6
7
-
## Constructor function
7
+
## Funções construtoras
8
8
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:
10
10
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"`.
13
13
14
-
For instance:
14
+
Por exemplo:
15
15
16
16
```js run
17
17
functionUser(name) {
@@ -27,182 +27,180 @@ alert(user.name); // Jack
27
27
alert(user.isAdmin); // false
28
28
```
29
29
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:
31
31
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.
35
35
36
-
In other words, `new User(...)`does something like:
36
+
Em outras palavras, `new User(...)`faz algo parecido com:
37
37
38
38
```js
39
39
functionUser(name) {
40
40
*!*
41
-
// this = {}; (implicitly)
41
+
// this = {}; (implicitamente)
42
42
*/!*
43
43
44
-
//add properties to this
44
+
//adiciona propriedades ao this
45
45
this.name= name;
46
46
this.isAdmin=false;
47
47
48
48
*!*
49
-
// return this; (implicitly)
49
+
// return this; (implicitamente)
50
50
*/!*
51
51
}
52
52
```
53
53
54
-
So`let user = new User("Jack")`gives the same result as:
54
+
Então,`let user = new User("Jack")`resulta no mesmo que:
55
55
56
56
```js
57
57
let user = {
58
58
name:"Jack",
59
-
isAdmin:false
59
+
isAdmin:false (falso)
60
60
};
61
61
```
62
62
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.
64
64
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.
66
66
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`.
68
68
69
69
````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:
71
71
72
72
```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() {
75
75
this.name = "John";
76
76
this.isAdmin = false;
77
77
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
81
81
};
82
82
```
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.
85
84
````
86
85
87
-
## Constructor mode test: new.target
86
+
## Teste para o modo construtor: new.target
88
87
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.
91
90
```
92
91
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`.
96
93
94
+
Ela é vazia para chamadas regulares e igual à função se esta foi chamada com ``new`:
97
95
```js run
98
96
functionUser() {
99
97
alert(new.target);
100
98
}
101
99
102
-
//without "new":
100
+
//sem "new":
103
101
*!*
104
102
User(); // undefined
105
103
*/!*
106
104
107
-
//with "new":
105
+
//com "new":
108
106
*!*
109
107
newUser(); // function User { ... }
110
108
*/!*
111
109
```
112
110
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" .
114
112
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:
116
114
117
115
```js run
118
116
functionUser(name) {
119
-
if (!new.target) { //if you run me without new
120
-
returnnewUser(name); // ...I will add new for you
117
+
if (!new.target) { //se você me executar sem new
118
+
returnnewUser(name); // ...eu irei adicioná-lo para você
121
119
}
122
120
123
121
this.name= name;
124
122
}
125
123
126
-
let john =User("John"); //redirects call to new User
124
+
let john =User("John"); //redireciona a chamada para new User
127
125
alert(john.name); // John
128
126
```
129
127
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á.
131
129
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.
133
131
134
-
## Return from constructors
132
+
## Return dentro de construtores
135
133
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.
137
135
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:
139
137
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.
142
140
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.
144
142
145
-
For instance, here`return`overrides `this`by returning an object:
143
+
Por exemplo, aqui,`return`sobrepõe o `this`retornando um objeto:
146
144
147
145
```js run
148
146
functionBigUser() {
149
147
150
148
this.name="John";
151
149
152
-
return { name:"Godzilla" }; // <-- returns this object
150
+
return { name:"Godzilla" }; // <-- retorna esse objeto
153
151
}
154
152
155
-
alert( newBigUser().name ); // Godzilla, got that object
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):
159
157
160
158
```js run
161
159
functionSmallUser() {
162
160
163
161
this.name="John";
164
162
165
-
return; // <-- returns this
163
+
return; // <-- retorna this
166
164
}
167
165
168
166
alert( newSmallUser().name ); // John
169
167
```
170
168
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.
172
170
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`:
175
173
176
174
```js
177
-
let user = new User; // <-- no parentheses
178
-
// same as
175
+
let user = new User; // <-- sem parênteses
176
+
// igual a
179
177
let user = new User();
180
178
```
181
179
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.
183
181
````
184
182
185
-
## Methods in constructor
183
+
## Métodos no construtor
186
184
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.
188
186
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.
190
188
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`:
192
190
193
191
```js run
194
192
functionUser(name) {
195
193
this.name= name;
196
194
197
195
this.sayHi=function() {
198
-
alert( "My name is: "+this.name );
196
+
alert( "Meu nome é: "+this.name );
199
197
};
200
198
}
201
199
202
200
*!*
203
201
let john =newUser("John");
204
202
205
-
john.sayHi(); //My name is: John
203
+
john.sayHi(); //Meu nome é: John
206
204
*/!*
207
205
208
206
/*
@@ -213,19 +211,19 @@ john = {
213
211
*/
214
212
```
215
213
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.
217
215
218
-
## Summary
216
+
## Sumário
219
217
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.
222
220
223
-
We can use constructor functions to make multiple similar objects.
221
+
Nós podemos usar funções construtoras para fazer diversos objetos iguais.
224
222
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.
226
224
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.
229
227
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>.
0 commit comments