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
Objects are usually created to represent entities of the real world, like users, orders and so on:
3
+
Objetos são geralmente criados para representar entidades do mundo real, como usuários, pedidos e assim por diante:
4
4
5
5
```js
6
6
let user = {
@@ -9,13 +9,13 @@ let user = {
9
9
};
10
10
```
11
11
12
-
And, in the real world, a user can *act*: select something from the shopping cart, login, logout etc.
12
+
E, no mundo real, um usuário pode *agir*: selecionar algo do carrinho de compras, fazer login, logout etc.
13
13
14
-
Actions are represented in JavaScript by functions in properties.
14
+
Ações são representadas em JavaScript por funções em propriedades.
15
15
16
-
## Method examples
16
+
## Exemplos de métodos
17
17
18
-
For a start, let's teach the`user`to say hello:
18
+
Para começar, vamos ensinar o`user`a dizer olá:
19
19
20
20
```js run
21
21
let user = {
@@ -25,84 +25,84 @@ let user = {
25
25
26
26
*!*
27
27
user.sayHi=function() {
28
-
alert("Hello!");
28
+
alert("Olá!");
29
29
};
30
30
*/!*
31
31
32
-
user.sayHi(); //Hello!
32
+
user.sayHi(); //Olá!
33
33
```
34
34
35
-
Here we've just used a Function Expression to create a function and assign it to the property `user.sayHi`of the object.
35
+
Aqui acabamos de usar uma Expressão de Função para criar uma função e atribuí-la à propriedade `user.sayHi`do objeto.
36
36
37
-
Then we can call it as `user.sayHi()`. The user can now speak!
37
+
Então podemos chamá-la como `user.sayHi()`. O usuário agora pode falar!
38
38
39
-
A function that is a property of an object is called its *method*.
39
+
Uma função que é uma propriedade de um objeto é chamada de seu *método*.
40
40
41
-
So, here we've got a method `sayHi`of the object`user`.
41
+
Então, aqui temos um método `sayHi`do objeto`user`.
42
42
43
-
Of course, we could use a pre-declared function as a method, like this:
43
+
Claro, poderíamos usar uma função pré-declarada como método, assim:
44
44
45
45
```js run
46
46
let user = {
47
47
// ...
48
48
};
49
49
50
50
*!*
51
-
//first, declare
51
+
//primeiro, declarar
52
52
functionsayHi() {
53
-
alert("Hello!");
53
+
alert("Olá!");
54
54
}
55
55
56
-
//then add as a method
56
+
//depois adicionar como um método
57
57
user.sayHi= sayHi;
58
58
*/!*
59
59
60
-
user.sayHi(); //Hello!
60
+
user.sayHi(); //Olá!
61
61
```
62
62
63
-
```smart header="Object-oriented programming"
64
-
When we write our code using objects to represent entities, that's called [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP".
63
+
```smart header="Programação orientada a objetos"
64
+
Quando escrevemos nosso código usando objetos para representar entidades, isso é chamado de [programação orientada a objetos](https://pt.wikipedia.org/wiki/Programação_orientada_a_objetos), em resumo: "POO".
65
65
66
-
OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E. Gamma, R. Helm, R. Johnson, J. Vissides or "Object-Oriented Analysis and Design with Applications" by G. Booch, and more.
66
+
POO é algo grande, uma ciência interessante por si só. Como escolher as entidades corretas? Como organizar a interação entre elas? Isso é arquitetura, e existem ótimos livros sobre esse tópico, como "Padrões de Projeto: Soluções Reutilizáveis de Software Orientado a Objetos" por E. Gamma, R. Helm, R. Johnson, J. Vissides ou "Análise e Projeto Orientados a Objetos com Aplicações" por G. Booch, entre outros.
67
67
```
68
-
### Method shorthand
68
+
### Sintaxe abreviada de método
69
69
70
-
There exists a shorter syntax for methods in an object literal:
70
+
Existe uma sintaxe mais curta para métodos em um literal de objeto:
71
71
72
72
```js
73
-
//these objects do the same
73
+
//esses objetos fazem a mesma coisa
74
74
75
75
user = {
76
76
sayHi:function() {
77
-
alert("Hello");
77
+
alert("Olá");
78
78
}
79
79
};
80
80
81
-
//method shorthand looks better, right?
81
+
//a sintaxe abreviada de método fica melhor, certo?
82
82
user = {
83
83
*!*
84
-
sayHi() { //same as "sayHi: function(){...}"
84
+
sayHi() { //mesmo que "sayHi: function(){...}"
85
85
*/!*
86
-
alert("Hello");
86
+
alert("Olá");
87
87
}
88
88
};
89
89
```
90
90
91
-
As demonstrated, we can omit `"function"`and just write`sayHi()`.
91
+
Como demonstrado, podemos omitir `"function"`e apenas escrever`sayHi()`.
92
92
93
-
To tell the truth, the notations are not fully identical. There are subtle differences related to object inheritance (to be covered later), but for now they do not matter. In almost all cases, the shorter syntax is preferred.
93
+
Para falar a verdade, as notações não são totalmente idênticas. Existem diferenças sutis relacionadas à herança de objetos (a ser coberta mais tarde), mas por enquanto elas não importam. Em quase todos os casos, a sintaxe mais curta é preferida.
94
94
95
-
## "this" in methods
95
+
## "this" em métodos
96
96
97
-
It's common that an object method needs to access the information stored in the object to do its job.
97
+
É comum que um método de objeto precise acessar as informações armazenadas no objeto para fazer seu trabalho.
98
98
99
-
For instance, the code inside `user.sayHi()`may need the name of the`user`.
99
+
Por exemplo, o código dentro de `user.sayHi()`pode precisar do nome do`user`.
100
100
101
-
**To access the object, a method can use the `this` keyword.**
101
+
**Para acessar o objeto, um método pode usar a palavra-chave `this`.**
102
102
103
-
The value of`this`is the object "before dot", the one used to call the method.
103
+
O valor de`this`é o objeto "antes do ponto", aquele usado para chamar o método.
104
104
105
-
For instance:
105
+
Por exemplo:
106
106
107
107
```js run
108
108
let user = {
@@ -111,7 +111,7 @@ let user = {
111
111
112
112
sayHi() {
113
113
*!*
114
-
// "this" is the "current object"
114
+
// "this" é o "objeto atual"
115
115
alert(this.name);
116
116
*/!*
117
117
}
@@ -121,9 +121,9 @@ let user = {
121
121
user.sayHi(); // John
122
122
```
123
123
124
-
Here during the execution of`user.sayHi()`, the value of`this`will be`user`.
124
+
Aqui, durante a execução de`user.sayHi()`, o valor de`this`será`user`.
125
125
126
-
Technically, it's also possible to access the object without `this`, by referencing it via the outer variable:
126
+
Tecnicamente, também é possível acessar o objeto sem `this`, referenciando-o através da variável externa:
127
127
128
128
```js
129
129
let user = {
@@ -132,16 +132,16 @@ let user = {
132
132
133
133
sayHi() {
134
134
*!*
135
-
alert(user.name); // "user" instead of "this"
135
+
alert(user.name); // "user" em vez de "this"
136
136
*/!*
137
137
}
138
138
139
139
};
140
140
```
141
141
142
-
...But such code is unreliable. If we decide to copy `user`to another variable, e.g. `admin = user`and overwrite`user`with something else, then it will access the wrong object.
142
+
...Mas tal código não é confiável. Se decidirmos copiar `user`para outra variável, por exemplo, `admin = user`e sobrescrever`user`com outra coisa, então ele acessará o objeto errado.
143
143
144
-
That's demonstrated below:
144
+
Isso é demonstrado abaixo:
145
145
146
146
```js run
147
147
let user = {
@@ -150,38 +150,38 @@ let user = {
150
150
151
151
sayHi() {
152
152
*!*
153
-
alert( user.name ); //leads to an error
153
+
alert( user.name ); //leva a um erro
154
154
*/!*
155
155
}
156
156
157
157
};
158
158
159
159
160
160
let admin = user;
161
-
user =null; //overwrite to make things obvious
161
+
user =null; //sobrescrevemos para tornar as coisas óbvias
162
162
163
163
*!*
164
164
admin.sayHi(); // TypeError: Cannot read property 'name' of null
165
165
*/!*
166
166
```
167
167
168
-
If we used `this.name`instead of `user.name`inside the`alert`, then the code would work.
168
+
Se usássemos `this.name`em vez de `user.name`dentro do`alert`, então o código funcionaria.
169
169
170
-
## "this" is not bound
170
+
## "this" não é vinculado
171
171
172
-
In JavaScript, keyword `this`behaves unlike most other programming languages. It can be used in any function, even if it's not a method of an object.
172
+
Em JavaScript, a palavra-chave `this`se comporta diferentemente da maioria das outras linguagens de programação. Ela pode ser usada em qualquer função, mesmo que não seja um método de um objeto.
173
173
174
-
There's no syntax error in the following example:
174
+
Não há erro de sintaxe no seguinte exemplo:
175
175
176
176
```js
177
177
functionsayHi() {
178
178
alert( *!*this*/!*.name );
179
179
}
180
180
```
181
181
182
-
The value of`this`is evaluated during the run-time, depending on the context.
182
+
O valor de`this`é avaliado durante o tempo de execução, dependendo do contexto.
183
183
184
-
For instance, here the same function is assigned to two different objects and has different "this" in the calls:
184
+
Por exemplo, aqui a mesma função é atribuída a dois objetos diferentes e tem "this" diferentes nas chamadas:
185
185
186
186
```js run
187
187
let user = { name:"John" };
@@ -192,23 +192,23 @@ function sayHi() {
192
192
}
193
193
194
194
*!*
195
-
//use the same function in two objects
195
+
//usa a mesma função em dois objetos
196
196
user.f= sayHi;
197
197
admin.f= sayHi;
198
198
*/!*
199
199
200
-
//these calls have different this
201
-
// "this" inside the function is the object "before the dot"
200
+
//essas chamadas têm this diferentes
201
+
// "this" dentro da função é o objeto "antes do ponto"
202
202
user.f(); // John (this == user)
203
203
admin.f(); // Admin (this == admin)
204
204
205
-
admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)
205
+
admin['f'](); // Admin (ponto ou colchetes acessam o método – não importa)
206
206
```
207
207
208
-
The rule is simple: if`obj.f()`is called, then`this`is`obj`during the call of`f`. So it's either `user`or`admin`in the example above.
208
+
A regra é simples: se`obj.f()`é chamado, então`this`é`obj`durante a chamada de`f`. Então é `user`ou`admin`no exemplo acima.
209
209
210
-
````smart header="Calling without an object: `this == undefined`"
211
-
We can even call the function without an object at all:
210
+
````smart header="Chamando sem um objeto: `this == undefined`"
211
+
Podemos até chamar a função sem um objeto:
212
212
213
213
```js run
214
214
functionsayHi() {
@@ -218,28 +218,28 @@ function sayHi() {
218
218
sayHi(); // undefined
219
219
```
220
220
221
-
In this case `this`is`undefined`in strict mode. If we try to access `this.name`, there will be an error.
221
+
Neste caso, `this`é`undefined`no modo estrito. Se tentarmos acessar `this.name`, haverá um erro.
222
222
223
-
In non-strict mode the value of `this`in such case will be the *global object* (`window`in a browser, we'll get to it later in the chapter [](info:global-object)). This is a historical behavior that`"use strict"`fixes.
223
+
No modo não estrito, o valor de `this`em tal caso será o *objeto global* (`window`em um navegador, chegaremos a isso mais tarde no capítulo [](info:global-object)). Este é um comportamento histórico que`"use strict"`corrige.
224
224
225
-
Usually such call is a programming error. If there's`this`inside a function, it expects to be called in an object context.
225
+
Geralmente tal chamada é um erro de programação. Se há`this`dentro de uma função, ela espera ser chamada em um contexto de objeto.
226
226
````
227
227
228
-
```smart header="The consequences of unbound `this`"
229
-
If you come from another programming language, then you are probably used to the idea of a "bound `this`", where methods defined in an object always have `this` referencing that object.
228
+
```smart header="As consequências do `this` não vinculado"
229
+
Se você vem de outra linguagem de programação, então provavelmente está acostumado com a ideia de um "`this` vinculado", onde métodos definidos em um objeto sempre têm `this` referenciando aquele objeto.
230
230
231
-
In JavaScript `this` is "free", its value is evaluated at call-time and does not depend on where the method was declared, but rather on what object is "before the dot".
231
+
Em JavaScript, `this` é "livre", seu valor é avaliado no momento da chamada e não depende de onde o método foi declarado, mas sim de qual objeto está "antes do ponto".
232
232
233
-
The concept of run-time evaluated `this` has both pluses and minuses. On the one hand, a function can be reused for different objects. On the other hand, the greater flexibility creates more possibilities for mistakes.
233
+
O conceito de `this` avaliado em tempo de execução tem prós e contras. Por um lado, uma função pode ser reutilizada para diferentes objetos. Por outro lado, a maior flexibilidade cria mais possibilidades para erros.
234
234
235
-
Here our position is not to judge whether this language design decision is good or bad. We'll understand how to work with it, how to get benefits and avoid problems.
235
+
Aqui nossa posição não é julgar se essa decisão de design da linguagem é boa ou ruim. Vamos entender como trabalhar com isso, como obter benefícios e evitar problemas.
236
236
```
237
237
238
-
## Arrow functions have no "this"
238
+
## Funções de seta não têm "this"
239
239
240
-
Arrow functions are special: they don't have their "own" `this`. If we reference `this` from such a function, it's taken from the outer "normal" function.
240
+
Funções de seta são especiais: elas não têm seu próprio `this`. Se referenciarmos `this` de tal função, ele é obtido da função "normal" externa.
241
241
242
-
For instance, here `arrow()` uses `this` from the outer `user.sayHi()` method:
242
+
Por exemplo, aqui `arrow()` usa `this` do método externo `user.sayHi()`:
243
243
244
244
```js run
245
245
let user = {
@@ -253,18 +253,18 @@ let user = {
253
253
user.sayHi(); // Ilya
254
254
```
255
255
256
-
That's a special feature of arrow functions, it's useful when we actually do not want to have a separate `this`, but rather to take it from the outer context. Later in the chapter <info:arrow-functions> we'll go more deeply into arrow functions.
256
+
Essa é uma característica especial das funções de seta, é útil quando na verdade não queremos ter um `this` separado, mas sim obtê-lo do contexto externo. Mais tarde no capítulo <info:arrow-functions> vamos mergulhar mais profundamente nas funções de seta.
257
257
258
258
259
-
## Summary
259
+
## Resumo
260
260
261
-
- Functions that are stored in object properties are called "methods".
262
-
- Methods allow objects to "act" like `object.doSomething()`.
263
-
- Methods can reference the object as `this`.
261
+
- Funções que são armazenadas em propriedades de objeto são chamadas de "métodos".
262
+
- Métodos permitem que objetos "ajam" como `object.doSomething()`.
263
+
- Métodos podem referenciar o objeto como `this`.
264
264
265
-
The value of `this` is defined at run-time.
266
-
- When a function is declared, it may use `this`, but that `this` has no value until the function is called.
267
-
- A function can be copied between objects.
268
-
- When a function is called in the "method" syntax: `object.method()`, the value of `this` during the call is `object`.
265
+
O valor de `this` é definido em tempo de execução.
266
+
- Quando uma função é declarada, ela pode usar `this`, mas esse `this` não tem valor até que a função seja chamada.
267
+
- Uma função pode ser copiada entre objetos.
268
+
- Quando uma função é chamada na sintaxe de "método": `object.method()`, o valor de `this` durante a chamada é `object`.
269
269
270
-
Please note that arrow functions are special: they have no `this`. When `this` is accessed inside an arrow function, it is taken from outside.
270
+
Por favor, note que funções de seta são especiais: elas não têm `this`. Quando `this` é acessado dentro de uma função de seta, ele é obtido de fora.
0 commit comments