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
alert( worker.slow(2) ); //Ups! Erro: Não é possível ler a 'someMethod' de indefinido
105
106
*/!*
106
107
```
107
108
108
-
The error occurs in the line `(*)`that tries to access`this.someMethod`and fails. Can you see why?
109
+
O erro ocorre na linha `(*)`que tenta acessar a`this.someMethod`e falha. Podemos ver por quê?
109
110
110
-
The reason is that the wrapper calls the original function as `func(x)`in the line `(**)`. And, when called like that, the function gets`this = undefined`.
111
+
A razão é que o embrulhador chama a função original como `func(x)`na linha `(**)`. E, quando chamada desta maneira, a função recebe`this = undefined`.
111
112
112
-
We would observe a similar symptom if we tried to run:
113
+
Observaríamos um sintoma semelhante se tentássemos executar:
113
114
114
115
```js
115
116
let func =worker.slow;
116
117
func(2);
117
118
```
118
119
119
-
So, the wrapper passes the call to the original method, but without the context`this`. Hence the error.
120
+
Assim, o embrulhador passa a chamada para o método original, mas sem o contexto`this`. Daí o erro.
120
121
121
-
Let's fix it.
122
+
Vamos corrigi-lo.
122
123
123
-
There's a special built-in function method [func.call(context, ...args)](mdn:js/Function/call)that allows to call a function explicitly setting`this`.
124
+
Existe uma método especial de função embutido [`func.call(context, ...args)`](mdn:js/Function/call)que permite chamar uma função definindo explicitamente`this`.
124
125
125
-
The syntax is:
126
+
A sintaxe é:
126
127
127
128
```js
128
129
func.call(context, arg1, arg2, ...)
129
130
```
130
131
131
-
It runs `func` providing the first argument as `this`, and the next as the arguments.
132
+
Ele executa `func` fornecendo o primeiro argumento como `this`, e o próximo como os argumentos.
133
+
134
+
Para simplificar, estas duas chamadas fazem quase o mesmo:
132
135
133
-
To put it simply, these two calls do almost the same:
134
136
```js
135
137
func(1, 2, 3);
136
138
func.call(obj, 1, 2, 3)
137
139
```
138
140
139
-
They both call `func`with arguments `1`, `2` and`3`. The only difference is that`func.call`also sets`this`to`obj`.
141
+
Ambas chamam `func`com os argumentos `1`, `2`, e`3`. A única diferença é que`func.call`também define`this`como`obj`.
140
142
141
-
As an example, in the code below we call `sayHi`in the context of different objects: `sayHi.call(user)`runs`sayHi`providing`this=user`, and the next line sets`this=admin`:
143
+
Como exemplo, no código abaixo chamamos `sayHi`no contexto de diferentes objetos: `sayHi.call(user)`executa`sayHi`fornecendo`this=user`, e a próxima linha define`this=admin`:
142
144
143
145
```js run
144
146
functionsayHi() {
@@ -148,13 +150,13 @@ function sayHi() {
148
150
let user = { name:"John" };
149
151
let admin = { name:"Admin" };
150
152
151
-
// use call to pass different objects as "this"
153
+
// usar `call` para passar
154
+
// diferentes objetos como "this"
152
155
sayHi.call( user ); // John
153
156
sayHi.call( admin ); // Admin
154
157
```
155
158
156
-
And here we use `call` to call `say` with the given context and phrase:
157
-
159
+
E aqui usamos `call` para chamar `say` com o dado contexto e frase:
158
160
159
161
```js run
160
162
functionsay(phrase) {
@@ -163,11 +165,12 @@ function say(phrase) {
163
165
164
166
let user = { name:"John" };
165
167
166
-
// user becomes this, and "Hello" becomes the first argument
168
+
// `user` torna-se `this`, e "Hello"
169
+
// torna-se o primeiro argumento
167
170
say.call( user, "Hello" ); // John: Hello
168
171
```
169
172
170
-
In our case, we can use `call`in the wrapper to pass the context to the original function:
173
+
No nosso caso, podemos usar `call`no embrulhador para passar o contexto para a função original:
171
174
172
175
```js run
173
176
let worker = {
@@ -188,26 +191,26 @@ function cachingDecorator(func) {
188
191
returncache.get(x);
189
192
}
190
193
*!*
191
-
let result =func.call(this, x); // "this" is passed correctly now
194
+
let result =func.call(this, x); // "this" é agora passado corretamente
192
195
*/!*
193
196
cache.set(x, result);
194
197
return result;
195
198
};
196
199
}
197
200
198
-
worker.slow=cachingDecorator(worker.slow); //now make it caching
alert( worker.slow(2) ); //works, doesn't call the original (cached)
203
+
alert( worker.slow(2) ); //funciona
204
+
alert( worker.slow(2) ); //funciona, não chama o original (memorizado)
202
205
```
203
206
204
-
Now everything is fine.
207
+
Agora está tudo bem.
205
208
206
-
To make it all clear, let's see more deeply how `this`is passed along:
209
+
Para tornar tudo mais claro, veremos mais profundamente como `this`é passado adiante:
207
210
208
-
1.After the decoration`worker.slow`is now the wrapper`function (x) { ... }`.
209
-
2.So when`worker.slow(2)`is executed, the wrapper gets`2`as an argument and `this=worker` (it's the object before dot).
210
-
3.Inside the wrapper, assuming the result is not yet cached, `func.call(this, x)`passes the current `this` (`=worker`) and the current argument (`=2`) to the original method.
211
+
1.Após a decoração,`worker.slow`agora é o embrulhador`function (x) { ... }`.
212
+
2.Então quando`worker.slow(2)`é executado, o embrulhador recebe`2`como argumento e `this=worker` (é o objeto antes do ponto).
213
+
3.Dentro do embrulhador, assumindo que o resultado ainda não está memorizado, `func.call(this, x)`passa o `this`atual (`=worker`) e o argumento atual (`=2`) para o método original.
0 commit comments