Skip to content

Commit eaf4956

Browse files
authored
Merge pull request #423 from danilolmc/update-reference-type
Reference Type
2 parents c883271 + b251d2c commit eaf4956

File tree

5 files changed

+70
-73
lines changed

5 files changed

+70
-73
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
1-
**Error**!
1+
**Erro**!
22

3-
Try it:
3+
Tente isso:
44

55
```js run
66
let user = {
77
name: "John",
88
go: function() { alert(this.name) }
99
}
1010

11-
(user.go)() // error!
11+
(user.go)() // erro!
1212
```
1313

14-
The error message in most browsers does not give us much of a clue about what went wrong.
14+
A mensagem de erro na maioria dos navegadores não fornece muita indicação sobra o que deu errado.
1515

16-
**The error appears because a semicolon is missing after `user = {...}`.**
16+
**O erro ocorre porque está faltando um ponto e vírgula após user = {...}.**
1717

18-
JavaScript does not auto-insert a semicolon before a bracket `(user.go)()`, so it reads the code like:
18+
JavaScript não insere automaticamente um ponto e vírgula antes de um colchete `(user.go)()`, então ele interpreta o código como:
1919

2020
```js no-beautify
2121
let user = { go:... }(user.go)()
2222
```
2323

24-
Then we can also see that such a joint expression is syntactically a call of the object `{ go: ... }` as a function with the argument `(user.go)`. And that also happens on the same line with `let user`, so the `user` object has not yet even been defined, hence the error.
24+
Então também podemos ver que tal expressão conjunta é sintaticamente uma chamada do objeto `{ go: ... }` como uma função com o argumento `(user.go)`. E isso também acontece na mesma linha com `let user`, então o objeto `user` ainda nem foi definido, daí o erro.
2525

26-
If we insert the semicolon, all is fine:
26+
Se inserirmos o ponto e vírgula, tudo fica bem:
2727

2828
```js run
2929
let user = {
@@ -34,4 +34,4 @@ let user = {
3434
(user.go)() // John
3535
```
3636

37-
Please note that parentheses around `(user.go)` do nothing here. Usually they setup the order of operations, but here the dot `.` works first anyway, so there's no effect. Only the semicolon thing matters.
37+
Por favor, note que os parênteses em torno de `(user.go)` não fazem nada aqui. Normalmente, eles estabelecem a ordem das operações, mas aqui o ponto `.` funciona primeiro de qualquer maneira, então não há efeito. A única coisa que importa é o ponto e vírgula.
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
importance: 2
1+
importância: 2
22

33
---
44

5-
# Syntax check
6-
7-
What is the result of this code?
5+
# Verificação de sintaxe
86

7+
Qual é o resultado deste código?
98

109
```js no-beautify
1110
let user = {
@@ -16,4 +15,4 @@ let user = {
1615
(user.go)()
1716
```
1817

19-
P.S. There's a pitfall :)
18+
P.S. Há uma pegadinha :)
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1+
Aqui estão as explicações.
12

2-
Here's the explanations.
3+
1. Isso é uma chamada de método de objeto regular.
34

4-
1. That's a regular object method call.
5+
2. O mesmo, parênteses não alteram a ordem das operações aqui, o ponto é executado primeiro de qualquer maneira.
56

6-
2. The same, parentheses do not change the order of operations here, the dot is first anyway.
7-
8-
3. Here we have a more complex call `(expression)()`. The call works as if it were split into two lines:
7+
3. Aqui temos uma chamada mais complexa (expressão)(). A chamada funciona como se estivesse dividida em duas linhas:
98

109
```js no-beautify
11-
f = obj.go; // calculate the expression
12-
f(); // call what we have
10+
f = obj.go; // calcula a expressão
11+
f(); // chama o que temos
1312
```
1413

15-
Here `f()` is executed as a function, without `this`.
16-
17-
4. The similar thing as `(3)`, to the left of the parentheses `()` we have an expression.
14+
Aqui, f() é executado como uma função, sem this.
1815

19-
To explain the behavior of `(3)` and `(4)` we need to recall that property accessors (dot or square brackets) return a value of the Reference Type.
16+
4. A coisa semelhante ao `(3)`, à esquerda dos parênteses `()` temos uma expressão.
2017

21-
Any operation on it except a method call (like assignment `=` or `||`) turns it into an ordinary value, which does not carry the information allowing to set `this`.
18+
Para explicar o comportamento de `(3)` e `(4)`, precisamos lembrar que os acessadores de propriedade (ponto ou colchetes) retornam um valor do Tipo de Referência.
2219

20+
Qualquer operação nele, exceto uma chamada de método (como a atribuição `=` ou `||`), o transforma em um valor comum, que não carrega a informação permitindo configurar `this`.

1-js/99-js-misc/04-reference-type/3-why-this/task.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
importance: 3
1+
importância: 3
22

33
---
44

5-
# Explain the value of "this"
5+
# Explique o valor de "this"
66

7-
In the code below we intend to call `obj.go()` method 4 times in a row.
7+
No código abaixo, pretendemos chamar o método `obj.go()` 4 vezes consecutivas.
88

9-
But calls `(1)` and `(2)` works differently from `(3)` and `(4)`. Why?
9+
Mas as chamadas `(1)` e `(2)` funcionam de maneira diferente de `(3)` e `(4)`. Por quê?
1010

1111
```js run no-beautify
1212
let obj, method;
+43-43
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11

2-
# Reference Type
2+
# Tipo de referência
33

4-
```warn header="In-depth language feature"
5-
This article covers an advanced topic, to understand certain edge-cases better.
4+
```warn header="Recurso aprofundado da linguagem"
5+
Este artigo aborda um tópico avançado para uma compreensão mais aprofundada de casos específicos.
66
7-
It's not important. Many experienced developers live fine without knowing it. Read on if you want to know how things work under the hood.
7+
Não é algo crucial. Muitos desenvolvedores experientes conseguem viver bem sem conhecê-lo. Continue lendo se desejar entender como as coisas funcionam internamente.
88
```
99

10-
A dynamically evaluated method call can lose `this`.
10+
Uma chamada de método avaliada dinamicamente pode perder a referência de `this`.
1111

12-
For instance:
12+
Por exemplo:
1313

1414
```js run
1515
let user = {
@@ -18,42 +18,42 @@ let user = {
1818
bye() { alert("Bye"); }
1919
};
2020

21-
user.hi(); // works
21+
user.hi(); // funciona
2222

23-
// now let's call user.hi or user.bye depending on the name
23+
// agora, vamos chamar user.hi ou user.bye dependendo do nome
2424
*!*
25-
(user.name == "John" ? user.hi : user.bye)(); // Error!
25+
(user.name == "John" ? user.hi : user.bye)(); // Erro!
2626
*/!*
2727
```
2828

29-
On the last line there is a conditional operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`.
29+
Na última linha, há um operador condicional que escolhe entre `user.hi` ou `user.bye`. Neste caso, o resultado é `user.hi`.
3030

31-
Then the method is immediately called with parentheses `()`. But it doesn't work correctly!
31+
Então, o método é imediatamente chamado com parênteses `()`. Mas não funciona corretamente!
3232

33-
As you can see, the call results in an error, because the value of `"this"` inside the call becomes `undefined`.
33+
Como você pode ver, a chamada resulta em um erro, porque o valor de `"this"` dentro da chamada se torna `undefined`.
3434

35-
This works (object dot method):
35+
Isso funciona (objeto, ponto, método):
3636
```js
3737
user.hi();
3838
```
3939

40-
This doesn't (evaluated method):
40+
Isso não funciona (método avaliado):
4141
```js
42-
(user.name == "John" ? user.hi : user.bye)(); // Error!
42+
(user.name == "John" ? user.hi : user.bye)(); // Erro!
4343
```
4444

45-
Why? If we want to understand why it happens, let's get under the hood of how `obj.method()` call works.
45+
Por quê? Se quisermos entender porque isso acontece, vamos nos aprofundar em como funciona a chamada `obj.method()` por debaixo dos panos.
4646

47-
## Reference type explained
47+
## Tipo por referência explicado
4848

49-
Looking closely, we may notice two operations in `obj.method()` statement:
49+
Observando de perto, podemos notar duas operações na instrução `obj.method()`:
5050

51-
1. First, the dot `'.'` retrieves the property `obj.method`.
52-
2. Then parentheses `()` execute it.
51+
1. Primeiro, o ponto `'.'` recupera a propriedade `obj.method`.
52+
2. Em seguida, os parênteses `()` o executam.
5353

54-
So, how does the information about `this` get passed from the first part to the second one?
54+
Então, como a informação sobre `this` é passada da primeira parte para a segunda?
5555

56-
If we put these operations on separate lines, then `this` will be lost for sure:
56+
Se colocarmos essas operações em linhas separadas, então `this` certamente será perdido:
5757

5858
```js run
5959
let user = {
@@ -62,47 +62,47 @@ let user = {
6262
};
6363

6464
*!*
65-
// split getting and calling the method in two lines
65+
// Divide a obtenção e a chamada do método em duas linhas
6666
let hi = user.hi;
67-
hi(); // Error, because this is undefined
67+
hi(); // Erro, pois é undefined
6868
*/!*
6969
```
7070

71-
Here `hi = user.hi` puts the function into the variable, and then on the last line it is completely standalone, and so there's no `this`.
71+
Aqui `hi = user.hi` coloca a função na variável, e então, na última linha, ela é completamente independente, e assim não há `this`.
7272

73-
**To make `user.hi()` calls work, JavaScript uses a trick -- the dot `'.'` returns not a function, but a value of the special [Reference Type](https://tc39.github.io/ecma262/#sec-reference-specification-type).**
73+
**Para fazer com que chamadas user.hi() funcionem, o JavaScript utiliza um truque: o ponto `.` não retorna uma função, mas um valor do [tipo por referência](https://tc39.github.io/ecma262/#sec-reference-specification-type) especial.**
7474

75-
The Reference Type is a "specification type". We can't explicitly use it, but it is used internally by the language.
75+
O tipo por referência é um "tipo de especificação". Não podemos usá-lo explicitamente, mas é utilizado internamente pela linguagem.
7676

77-
The value of Reference Type is a three-value combination `(base, name, strict)`, where:
77+
O valor do tipo de referência é uma combinação de três valores `(base, name, strict)`, onde:
7878

79-
- `base` is the object.
80-
- `name` is the property name.
81-
- `strict` is true if `use strict` is in effect.
79+
- `base` é o objeto.
80+
- `name` é o nome da propriedade.
81+
- `strict` é verdadeiro se `use strict` estiver em efeito.
8282

83-
The result of a property access `user.hi` is not a function, but a value of Reference Type. For `user.hi` in strict mode it is:
83+
O resultado de um acesso à propriedade `user.hi` não é uma função, mas um valor de tipo de referência. Para `user.hi` em modo estrito (strict mode), é:
8484

8585
```js
86-
// Reference Type value
86+
// valor do Tipo de Referência
8787
(user, "hi", true)
8888
```
8989

90-
When parentheses `()` are called on the Reference Type, they receive the full information about the object and its method, and can set the right `this` (`user` in this case).
90+
Quando parênteses são chamados no tipo de referência, eles recebem todas as informações sobre o objeto e o seu método, e podem definir o `this` correto (`user` nesse caso).
9191

92-
Reference type is a special "intermediary" internal type, with the purpose to pass information from dot `.` to calling parentheses `()`.
92+
O tipo de referência é um tipo interno especial "intermediário", com o propósito de transmitir informações do ponto `.` para os parênteses de chamada `()`.
9393

94-
Any other operation like assignment `hi = user.hi` discards the reference type as a whole, takes the value of `user.hi` (a function) and passes it on. So any further operation "loses" `this`.
94+
Qualquer outra operação, como a atribuição `hi = user.hi`, descarta o tipo de referência como um todo, pega o valor de `user.hi` (uma função) e o repassa. Portanto, qualquer operação subsequente "perde" o `this`.
9595

96-
So, as the result, the value of `this` is only passed the right way if the function is called directly using a dot `obj.method()` or square brackets `obj['method']()` syntax (they do the same here). There are various ways to solve this problem such as [func.bind()](/bind#solution-2-bind).
96+
Então, como resultado, o valor de `this` é apenas passado corretamente apenas se a função for chamada diretamente usando a sintaxe de ponto `obj.method()` ou colchetes `obj['method']()` (ambas fazem o mesmo aqui). Existem várias maneiras de resolver esse problema, como [func.bind()](/bind#solution-2-bind).
9797

98-
## Summary
98+
## Resumo
9999

100-
Reference Type is an internal type of the language.
100+
O Tipo de referência é um tipo interno da linguagem.
101101

102-
Reading a property, such as with dot `.` in `obj.method()` returns not exactly the property value, but a special "reference type" value that stores both the property value and the object it was taken from.
102+
Ler uma propriedade, como com o ponto `.` em `obj.method()` não retorna exatamente o valor da propriedade, mas um valor especial do "tipo de referência" que armazena tanto o valor da propriedade quanto o objeto do qual foi extraído.
103103

104-
That's for the subsequent method call `()` to get the object and set `this` to it.
104+
Isso é para a subsequente chamada de método `()` obter o objeto e definir `this` para ele.
105105

106-
For all other operations, the reference type automatically becomes the property value (a function in our case).
106+
Para todas as outras operações, o tipo de referência automaticamente se torna o valor da propriedade (uma função no nosso caso).
107107

108-
The whole mechanics is hidden from our eyes. It only matters in subtle cases, such as when a method is obtained dynamically from the object, using an expression.
108+
Toda a mecânica está oculta aos nossos olhos. Isso é relevante em casos sutis, como quando um método é obtido dinamicamente a partir do objeto, usando uma expressão.

0 commit comments

Comments
 (0)