Skip to content

Commit a75c9f4

Browse files
committed
docs: finish the translation of call-apply-decorators article
1 parent fe966ce commit a75c9f4

File tree

1 file changed

+49
-49
lines changed
  • 1-js/06-advanced-functions/09-call-apply-decorators

1 file changed

+49
-49
lines changed

1-js/06-advanced-functions/09-call-apply-decorators/article.md

+49-49
Original file line numberDiff line numberDiff line change
@@ -287,83 +287,83 @@ Existem duas alterações:
287287
- 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.
288288
- 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.
289289

290-
## func.apply
290+
## `func.apply`
291291

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)`.
293293

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) é:
295295

296296
```js
297297
func.apply(context, args)
298298
```
299299

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

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

304-
So these two calls are almost equivalent:
304+
Assim, estas duas chamadas são quase equivalentes:
305305

306306
```js
307307
func.call(context, ...args);
308308
func.apply(context, args);
309309
```
310310

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

313-
There's only a subtle difference regarding `args`:
313+
Existe apenas uma diferença subtil em relação a `args`:
314314

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

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

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

322-
That's the simplest form of it:
322+
Esta é a maneira mais simples de o fazer:
323323

324324
```js
325325
let wrapper = function() {
326326
return func.apply(this, arguments);
327327
};
328328
```
329329

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

332-
## Borrowing a method [#method-borrowing]
332+
## Emprestando um método [#method-borrowing]
333333

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

336336
```js
337337
function hash(args) {
338338
return args[0] + ',' + args[1];
339339
}
340340
```
341341

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

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):
345345

346346
```js
347347
function hash(args) {
348348
return args.join();
349349
}
350350
```
351351

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

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

356356
```js run
357357
function hash() {
358358
*!*
359-
alert( arguments.join() ); // Error: arguments.join is not a function
359+
alert( arguments.join() ); // Error: `arguments.join` não é uma função
360360
*/!*
361361
}
362362

363363
hash(1, 2);
364364
```
365365

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

368368
```js run
369369
function hash() {
@@ -375,55 +375,55 @@ function hash() {
375375
hash(1, 2);
376376
```
377377

378-
The trick is called *method borrowing*.
378+
O truque chama-se *empréstimo de método*.
379379

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

382-
Why does it work?
382+
Por que é que funciona?
383383

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

386-
Taken from the specification almost "as-is":
386+
Retirado da especificação quase "tal e qual":
387387

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

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

398-
## Decorators and function properties
398+
## Decoradores e propriedades de função
399399

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

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

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

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

408-
## Summary
408+
## Sumário
409409

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

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

414-
To implement `cachingDecorator`, we studied methods:
414+
Para implementar `cachingDecorator`, estudámos os métodos:
415415

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

419-
The generic *call forwarding* is usually done with `apply`:
419+
O *encaminhamento de chamada* genérico é normalmente efetuado com `apply`:
420420

421421
```js
422422
let wrapper = function() {
423423
return original.apply(this, arguments);
424424
};
425425
```
426426

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

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

Comments
 (0)