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
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/09-call-apply-decorators/article.md
+49-49
Original file line number
Diff line number
Diff line change
@@ -287,83 +287,83 @@ Existem duas alterações:
287
287
- Na linha `(*)` chama `hash` para criar uma única chave a partir de `arguments`. Neste caso usamos uma função simples de "junção" que transforma os argumentos `(3,5)` na chave `"3,5"`. Os casos mais complexos podem exigir outras funções de baralhamento.
288
288
- Então `(**)` usa `func.call(this, ...arguments)` para passar tanto o contexto quanto todos os argumentos que o embrulhador recebeu (não apenas o primeiro) para a função original.
289
289
290
-
## func.apply
290
+
## `func.apply`
291
291
292
-
Instead of `func.call(this, ...arguments)`we could use`func.apply(this, arguments)`.
292
+
Em vez de `func.call(this, ...arguments)`poderíamos usar`func.apply(this, arguments)`.
293
293
294
-
The syntax of built-in method [func.apply](mdn:js/Function/apply)is:
294
+
A sintaxe do método embutido [`func.apply`](mdn:js/Function/apply)é:
295
295
296
296
```js
297
297
func.apply(context, args)
298
298
```
299
299
300
-
It runs the`func`setting`this=context`and using an array-like object `args`as the list of arguments.
300
+
Este executa a`func`definindo`this=context`e usando um objeto parecido com vetor `args`como lista de argumentos.
301
301
302
-
The only syntax difference between `call`and`apply`is that`call`expects a list of arguments, while`apply`takes an array-like object with them.
302
+
A única diferença entre `call`e`apply`é que`call`espera uma lista de argumentos, enquanto`apply`recebe um objeto parecido com vetor com eles.
303
303
304
-
So these two calls are almost equivalent:
304
+
Assim, estas duas chamadas são quase equivalentes:
305
305
306
306
```js
307
307
func.call(context, ...args);
308
308
func.apply(context, args);
309
309
```
310
310
311
-
They perform the same call of`func`with given context and arguments.
311
+
Estas realizam a mesma chama de`func`com dado contexto e argumentos.
312
312
313
-
There's only a subtle difference regarding`args`:
313
+
Existe apenas uma diferença subtil em relação a`args`:
314
314
315
-
-The spread syntax `...`allows to pass *iterable*`args`as the list to`call`.
316
-
-The`apply`accepts only *array-like*`args`.
315
+
-A sintaxe de propagação `...`permite passar `args`*iteráveis* como lista a`call`.
316
+
-O`apply`aceita apenas `args`*parecidos com vetor*.
317
317
318
-
...And for objects that are both iterable and array-like, such as a real array, we can use any of them, but`apply`will probably be faster, because most JavaScript engines internally optimize it better.
318
+
...E para objetos que são simultaneamente iteráveis e semelhantes a um vetor, tais como um vetor de verdade, podemos usar qualquer um destes, mas`apply`será provavelmente mais rápido, porque a maioria dos motores de JavaScript otimizam-o internamente melhor.
319
319
320
-
Passing all arguments along with the context to another function is called *call forwarding*.
320
+
A passagem de todos os argumentos juntamente com o contexto a outra função chama-se **encaminhamento de chamada**.
321
321
322
-
That's the simplest form of it:
322
+
Esta é a maneira mais simples de o fazer:
323
323
324
324
```js
325
325
letwrapper=function() {
326
326
returnfunc.apply(this, arguments);
327
327
};
328
328
```
329
329
330
-
When an external code calls such`wrapper`, it is indistinguishable from the call of the original function`func`.
330
+
Quando um código externo chama este`wrapper`, é indistinguível da chamada da função original `func`.
331
331
332
-
## Borrowing a method[#method-borrowing]
332
+
## Emprestando um método[#method-borrowing]
333
333
334
-
Now let's make one more minor improvement in the hashing function:
334
+
Agora vamos fazer mais uma pequena melhoria na função de baralhamento:
335
335
336
336
```js
337
337
functionhash(args) {
338
338
return args[0] +','+ args[1];
339
339
}
340
340
```
341
341
342
-
As of now, it works only on two arguments. It would be better if it could glue any number of`args`.
342
+
De momento, funciona apenas com dois argumentos. Seria melhor se pudesse colar qualquer número de`args`.
343
343
344
-
The natural solution would be to use [arr.join](mdn:js/Array/join) method:
344
+
A solução natural seria usar o método [`arr.join`](mdn:js/Array/join):
345
345
346
346
```js
347
347
functionhash(args) {
348
348
returnargs.join();
349
349
}
350
350
```
351
351
352
-
...Unfortunately, that won't work. Because we are calling `hash(arguments)`, and `arguments`object is both iterable and array-like, but not a real array.
352
+
...Infelizmente, isso não funcionará. Porque estamos chamando `hash(arguments)`, e o objeto `arguments`é tanto iterável quanto semelhante a um vetor, mas não um vetor de verdade.
353
353
354
-
So calling `join`on it would fail, as we can see below:
354
+
Por isso, chamar `join`sobre este falharia, como podemos ver abaixo:
355
355
356
356
```js run
357
357
functionhash() {
358
358
*!*
359
-
alert( arguments.join() ); // Error: arguments.join is not a function
359
+
alert( arguments.join() ); // Error: `arguments.join` não é uma função
360
360
*/!*
361
361
}
362
362
363
363
hash(1, 2);
364
364
```
365
365
366
-
Still, there's an easy way to use array join:
366
+
No entanto, existe uma maneira fácil de usar a junção de vetor:
367
367
368
368
```js run
369
369
functionhash() {
@@ -375,55 +375,55 @@ function hash() {
375
375
hash(1, 2);
376
376
```
377
377
378
-
The trick is called *method borrowing*.
378
+
O truque chama-se *empréstimo de método*.
379
379
380
-
We take (borrow) a join method from a regular array (`[].join`) and use`[].join.call` to run it in the context of`arguments`.
380
+
Nós pegamos (emprestamos) um método de junção dum vetor normal (`[].join`) e usamos`[].join.call()` para executá-lo no contexto de`arguments`.
381
381
382
-
Why does it work?
382
+
Por que é que funciona?
383
383
384
-
That's because the internal algorithm of the native method`arr.join(glue)`is very simple.
384
+
Isto acontece porque o algoritmo interno do método nativo`arr.join(glue)`é muito simples.
385
385
386
-
Taken from the specification almost "as-is":
386
+
Retirado da especificação quase "tal e qual":
387
387
388
-
1.Let`glue`be the first argument or, if no arguments, then a comma`","`.
389
-
2.Let`result`be an empty string.
390
-
3.Append`this[0]`to`result`.
391
-
4.Append`glue`and`this[1]`.
392
-
5.Append`glue`and`this[2]`.
393
-
6. ...Do so until `this.length`items are glued.
394
-
7.Return`result`.
388
+
1.Deixar`glue`ser o primeiro argumento, ou se não existirem argumentos, então uma vírgula`","`.
389
+
2.Deixar`result`ser uma sequência de caracteres vazia.
390
+
3.Anexar`this[0]`ao`result`.
391
+
4.Anexar`glue`e`this[1]`.
392
+
5.Anexar`glue`e`this[2]`.
393
+
6. ...Fazer isto até que itens de `this.length`estejam colados.
394
+
7.Retornar`result`.
395
395
396
-
So, technically it takes`this`and joins`this[0]`, `this[1]` ...etc together. It's intentionally written in a way that allows any array-like `this`(not a coincidence, many methods follow this practice). That's why it also works with`this=arguments`.
396
+
Então, tecnicamente este recebe`this`e junta`this[0]`, `this[1]` ...etc. Foi intencionalmente escrito de maneira a permitir qualquer `this`parecido com vetor (não por coincidência, muitos métodos seguem essa prática). É por isto que este também funciona com`this=arguments`.
397
397
398
-
## Decorators and function properties
398
+
## Decoradores e propriedades de função
399
399
400
-
It is generally safe to replace a function or a method with a decorated one, except for one little thing. If the original function had properties on it, like`func.calledCount`or whatever, then the decorated one will not provide them. Because that is a wrapper. So one needs to be careful if one uses them.
400
+
É geralmente seguro substituir uma função ou um método por um decorado, exceto por uma pequena coisa. Se a função original tinha propriedades, como`func.calledCount`ou qualquer outra, então a função decorada não as fornecerá. Porque isso é um embrulhador. Portanto, é preciso ter cuidado ao usá-las.
401
401
402
-
E.g. in the example above if `slow`function had any properties on it, then`cachingDecorator(slow)`is a wrapper without them.
402
+
Por exemplo, no exemplo acima se a função `slow`tivesse algum propriedade, então`cachingDecorator(slow)`é um embrulhador sem estas.
403
403
404
-
Some decorators may provide their own properties. E.g. a decorator may count how many times a function was invoked and how much time it took, and expose this information via wrapper properties.
404
+
Alguns decoradores podem fornecer as suas propriedades. Por exemplo, um decorador pode contar quantas vezes uma função foi invocada e quanto tempo demorou, e expor esta informação através das propriedades do embrulhador.
405
405
406
-
There exists a way to create decorators that keep access to function properties, but this requires using a special`Proxy`object to wrap a function. We'll discuss it later in the article<info:proxy#proxy-apply>.
406
+
Existe uma maneira de criar decoradores que preservam o acesso às propriedades das funções, mas isso exige usar um objeto`Proxy`especial para embrulhar uma função. Nós discutiremos isso mais tarde no artigo<info:proxy#proxy-apply>.
407
407
408
-
## Summary
408
+
## Sumário
409
409
410
-
*Decorator* is a wrapper around a function that alters its behavior. The main job is still carried out by the function.
410
+
O *decorador* é um embrulhador em torno duma função que altera o seu comportamento. O trabalho principal continua a ser efetuado pela função.
411
411
412
-
Decorators can be seen as "features" or "aspects" that can be added to a function. We can add one or add many. And all this without changing its code!
412
+
Os decoradores podem ser vistos como "características" ou "aspetos" que podem ser adicionados a uma função. Nós podemos adicionar um ou mais. E tudo isto sem alterar o seu código!
413
413
414
-
To implement`cachingDecorator`, we studied methods:
414
+
Para implementar`cachingDecorator`, estudámos os métodos:
415
415
416
-
-[func.call(context, arg1, arg2...)](mdn:js/Function/call)-- calls`func`with given context and arguments.
417
-
-[func.apply(context, args)](mdn:js/Function/apply)-- calls`func`passing`context`as`this`and array-like `args`into a list of arguments.
416
+
-[`func.call(context, arg1, arg2...)`](mdn:js/Function/call)— chama`func`com o contexto e argumentos fornecidos.
417
+
-[`func.apply(context, args)`](mdn:js/Function/apply)— chama`func`passando`context`como`this`e `args`parecido com vetor numa lista de argumentos.
418
418
419
-
The generic *call forwarding* is usually done with`apply`:
419
+
O *encaminhamento de chamada* genérico é normalmente efetuado com`apply`:
420
420
421
421
```js
422
422
letwrapper=function() {
423
423
returnoriginal.apply(this, arguments);
424
424
};
425
425
```
426
426
427
-
We also saw an example of *method borrowing* when we take a method from an object and `call` it in the context of another object. It is quite common to take array methods and apply them to `arguments`. The alternative is to use rest parameters object that is a real array.
427
+
Também vimos um exemplo de **empréstimo de método** quando pegamos um método dum objeto e o chamamos no contexto de outro objeto. É muito comum pegar em métodos de vetor e aplicá-los a `arguments`. A alternativa é usar o objeto de parâmetros restantes que é um vetor de verdade.
428
428
429
-
There are many decorators there in the wild. Check how well you got them by solving the tasks of this chapter.
429
+
Existem muitos decoradores à disposição. Nós podemos verificar se os conseguimos entender resolvendo as tarefas deste capítulo.
0 commit comments