Skip to content

Commit 889dbfc

Browse files
committed
Translate object methods article to Portuguese
1 parent e09c689 commit 889dbfc

1 file changed

Lines changed: 77 additions & 77 deletions

File tree

Lines changed: 77 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# Object methods, "this"
1+
# Métodos de objeto, "this"
22

3-
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:
44

55
```js
66
let user = {
@@ -9,13 +9,13 @@ let user = {
99
};
1010
```
1111

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.
1313

14-
Actions are represented in JavaScript by functions in properties.
14+
Ações são representadas em JavaScript por funções em propriedades.
1515

16-
## Method examples
16+
## Exemplos de métodos
1717

18-
For a start, let's teach the `user` to say hello:
18+
Para começar, vamos ensinar o `user` a dizer olá:
1919

2020
```js run
2121
let user = {
@@ -25,84 +25,84 @@ let user = {
2525

2626
*!*
2727
user.sayHi = function() {
28-
alert("Hello!");
28+
alert("Olá!");
2929
};
3030
*/!*
3131

32-
user.sayHi(); // Hello!
32+
user.sayHi(); // Olá!
3333
```
3434

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.
3636

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!
3838

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*.
4040

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`.
4242

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:
4444

4545
```js run
4646
let user = {
4747
// ...
4848
};
4949

5050
*!*
51-
// first, declare
51+
// primeiro, declarar
5252
function sayHi() {
53-
alert("Hello!");
53+
alert("Olá!");
5454
}
5555

56-
// then add as a method
56+
// depois adicionar como um método
5757
user.sayHi = sayHi;
5858
*/!*
5959

60-
user.sayHi(); // Hello!
60+
user.sayHi(); // Olá!
6161
```
6262

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".
6565
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.
6767
```
68-
### Method shorthand
68+
### Sintaxe abreviada de método
6969

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:
7171

7272
```js
73-
// these objects do the same
73+
// esses objetos fazem a mesma coisa
7474

7575
user = {
7676
sayHi: function() {
77-
alert("Hello");
77+
alert("Olá");
7878
}
7979
};
8080

81-
// method shorthand looks better, right?
81+
// a sintaxe abreviada de método fica melhor, certo?
8282
user = {
8383
*!*
84-
sayHi() { // same as "sayHi: function(){...}"
84+
sayHi() { // mesmo que "sayHi: function(){...}"
8585
*/!*
86-
alert("Hello");
86+
alert("Olá");
8787
}
8888
};
8989
```
9090

91-
As demonstrated, we can omit `"function"` and just write `sayHi()`.
91+
Como demonstrado, podemos omitir `"function"` e apenas escrever `sayHi()`.
9292

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.
9494

95-
## "this" in methods
95+
## "this" em métodos
9696

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.
9898

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`.
100100

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`.**
102102

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.
104104

105-
For instance:
105+
Por exemplo:
106106

107107
```js run
108108
let user = {
@@ -111,7 +111,7 @@ let user = {
111111

112112
sayHi() {
113113
*!*
114-
// "this" is the "current object"
114+
// "this" é o "objeto atual"
115115
alert(this.name);
116116
*/!*
117117
}
@@ -121,9 +121,9 @@ let user = {
121121
user.sayHi(); // John
122122
```
123123

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`.
125125

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:
127127

128128
```js
129129
let user = {
@@ -132,16 +132,16 @@ let user = {
132132

133133
sayHi() {
134134
*!*
135-
alert(user.name); // "user" instead of "this"
135+
alert(user.name); // "user" em vez de "this"
136136
*/!*
137137
}
138138

139139
};
140140
```
141141

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.
143143

144-
That's demonstrated below:
144+
Isso é demonstrado abaixo:
145145

146146
```js run
147147
let user = {
@@ -150,38 +150,38 @@ let user = {
150150

151151
sayHi() {
152152
*!*
153-
alert( user.name ); // leads to an error
153+
alert( user.name ); // leva a um erro
154154
*/!*
155155
}
156156

157157
};
158158

159159

160160
let admin = user;
161-
user = null; // overwrite to make things obvious
161+
user = null; // sobrescrevemos para tornar as coisas óbvias
162162

163163
*!*
164164
admin.sayHi(); // TypeError: Cannot read property 'name' of null
165165
*/!*
166166
```
167167

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.
169169

170-
## "this" is not bound
170+
## "this" não é vinculado
171171

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.
173173

174-
There's no syntax error in the following example:
174+
Não há erro de sintaxe no seguinte exemplo:
175175

176176
```js
177177
function sayHi() {
178178
alert( *!*this*/!*.name );
179179
}
180180
```
181181

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.
183183

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:
185185

186186
```js run
187187
let user = { name: "John" };
@@ -192,23 +192,23 @@ function sayHi() {
192192
}
193193

194194
*!*
195-
// use the same function in two objects
195+
// usa a mesma função em dois objetos
196196
user.f = sayHi;
197197
admin.f = sayHi;
198198
*/!*
199199

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"
202202
user.f(); // John (this == user)
203203
admin.f(); // Admin (this == admin)
204204

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)
206206
```
207207

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.
209209

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:
212212

213213
```js run
214214
function sayHi() {
@@ -218,28 +218,28 @@ function sayHi() {
218218
sayHi(); // undefined
219219
```
220220

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.
222222

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.
224224

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.
226226
````
227227
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.
230230
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".
232232
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.
234234
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.
236236
```
237237
238-
## Arrow functions have no "this"
238+
## Funções de seta não têm "this"
239239
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.
241241
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()`:
243243
244244
```js run
245245
let user = {
@@ -253,18 +253,18 @@ let user = {
253253
user.sayHi(); // Ilya
254254
```
255255
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.
257257
258258
259-
## Summary
259+
## Resumo
260260
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`.
264264
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`.
269269
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

Comments
 (0)