Skip to content

Commit d936142

Browse files
docs: translate the new function syntax article
The "new Function" syntax
2 parents 7b8bd10 + 8c915f8 commit d936142

File tree

1 file changed

+40
-40
lines changed
  • 1-js/06-advanced-functions/07-new-function

1 file changed

+40
-40
lines changed
+40-40
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,60 @@
11

2-
# The "new Function" syntax
2+
# A sintaxe de "new Function"
33

4-
There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
4+
Existe mais uma maneira de criar uma função. Ela é raramente usada, mas às vezes não existem alternativas.
55

6-
## Syntax
6+
## Sintaxe
77

8-
The syntax for creating a function:
8+
A sintaxe para criar uma função:
99

1010
```js
1111
let func = new Function ([arg1, arg2, ...argN], functionBody);
1212
```
1313

14-
The function is created with the arguments `arg1...argN` and the given `functionBody`.
14+
A função é criada com os argumentos `arg1...argN` e entregue para `functionBody`.
1515

16-
It's easier to understand by looking at an example. Here's a function with two arguments:
16+
É mais fácil de compreender olhando um exemplo. Aqui está uma função com dois argumentos:
1717

1818
```js run
1919
let sum = new Function('a', 'b', 'return a + b');
2020

2121
alert( sum(1, 2) ); // 3
2222
```
2323

24-
And here there's a function without arguments, with only the function body:
24+
E aqui está uma função sem argumentos, apenas com o corpo da função:
2525

2626
```js run
27-
let sayHi = new Function('alert("Hello")');
27+
let sayHi = new Function('alert("Olá")');
2828

29-
sayHi(); // Hello
29+
sayHi(); // Olá
3030
```
3131

32-
The major difference from other ways we've seen is that the function is created literally from a string, that is passed at run time.
32+
A principal diferença de outras formas que vimos é a função ser criada literalmente a partir de uma string, e passada em tempo de execução.
3333

34-
All previous declarations required us, programmers, to write the function code in the script.
34+
Todas as declarações anteriores requeriam de nós, programadores, escrever o código da função dentro do *script*.
3535

36-
But `new Function` allows to turn any string into a function. For example, we can receive a new function from a server and then execute it:
36+
Mas `new Function` permite transformar qualquer `string` em uma função. Por exemplo, nós podemos receber uma nova função de um servidor e executa-la:
3737

3838
```js
39-
let str = ... receive the code from a server dynamically ...
39+
let str = ... recebe o código de um servidor dinamicamente ...
4040

4141
let func = new Function(str);
4242
func();
4343
```
4444

45-
It is used in very specific cases, like when we receive code from a server, or to dynamically compile a function from a template, in complex web-applications.
45+
É usado em casos muito específicos, como quando recebemos código de um servidor, ou para compilar dinamicamente uma função a partir de um template, em aplicações web complexas.
4646

4747
## Closure
4848

49-
Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created (we covered that in the chapter <info:closure>).
49+
Normalmente, uma função lembra onde nasceu na propriedade especial `[[Environment]]`. Ela faz referência ao Ambiente Lexical de onde foi criado (abordaremos isso no capítulo <info:closure>).
5050

51-
But when a function is created using `new Function`, its `[[Environment]]` is set to reference not the current Lexical Environment, but the global one.
51+
Mas quando uma função é criada usando `new Function`, seu `[[Environment]]` é definido para fazer referência não ao Ambiente Lexical atual, mas ao ambiente global.
5252

53-
So, such function doesn't have access to outer variables, only to the global ones.
53+
Portanto, tal função não tem acesso a variáveis ​​externas, apenas a variáveis globais.
5454

5555
```js run
5656
function getFunc() {
57-
let value = "test";
57+
let value = "teste";
5858

5959
*!*
6060
let func = new Function('alert(value)');
@@ -63,14 +63,14 @@ function getFunc() {
6363
return func;
6464
}
6565

66-
getFunc()(); // error: value is not defined
66+
getFunc()(); // erro: value não foi definido
6767
```
6868

69-
Compare it with the regular behavior:
69+
Compare-a com o comportamento padrão:
7070

7171
```js run
7272
function getFunc() {
73-
let value = "test";
73+
let value = "teste";
7474

7575
*!*
7676
let func = function() { alert(value); };
@@ -79,45 +79,45 @@ function getFunc() {
7979
return func;
8080
}
8181

82-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82+
getFunc()(); // *!*"teste"*/!*, do escopo léxico de getFunc
8383
```
8484

85-
This special feature of `new Function` looks strange, but appears very useful in practice.
85+
Essa característica especial de `new Function` parece estranha, mas se apresenta muito útil, na prática.
8686

87-
Imagine that we must create a function from a string. The code of that function is not known at the time of writing the script (that's why we don't use regular functions), but will be known in the process of execution. We may receive it from the server or from another source.
87+
Imagine que nós precisamos criar uma função a partir de uma `string`. O código dessa função é desconhecido durante a escrita do *script* (por esse motivo, nós não usamos funções regulares), mas vai ser conhecido durante o processo de execução. Nós podemos receber do servidor ou de outra fonte.
8888

89-
Our new function needs to interact with the main script.
89+
Nossa nova função precisa interagir com o *script* principal.
9090

91-
What if it could access the outer variables?
91+
E se você pudesse acessar as variáveis ​​externas?
9292

93-
The problem is that before JavaScript is published to production, it's compressed using a *minifier* -- a special program that shrinks code by removing extra comments, spaces and -- what's important, renames local variables into shorter ones.
93+
O problema é que antes de o JavaScript ser publicado para produção, ele é comprimido usando um "minificador" -- um programa especial que encolhe código removendo comentários, espaços e -- o mais importante, renomeia variáveis locais em variáveis mais curtas.
9494

95-
For instance, if a function has `let userName`, minifier replaces it with `let a` (or another letter if this one is occupied), and does it everywhere. That's usually a safe thing to do, because the variable is local, nothing outside the function can access it. And inside the function, minifier replaces every mention of it. Minifiers are smart, they analyze the code structure, so they don't break anything. They're not just a dumb find-and-replace.
95+
Por exemplo, se uma função tem uma variável `let userName`, o minificador a troca por `let a` (ou outra letra se esta estiver ocupada), e ele faz isso em toda parte. Isso usualmente é uma coisa segura de se fazer, por a variável ser local, nada fora da função pode acessar ela. E dentro da função, o minificador troca todas as suas menções. Minificadores são inteligentes, eles analisam a estrutura do código, para que eles não quebrem nada. Eles não são um simples não-inteligente "encontra-e-substitui".
9696

97-
So if `new Function` had access to outer variables, it would be unable to find renamed `userName`.
97+
Portanto, se `new Function` tivesse acesso a variáveis ​​externas, não seria possível encontrar `userName` renomeado.
9898

99-
**If `new Function` had access to outer variables, it would have problems with minifiers.**
99+
**Se a `new Function` tivesse acesso a variáveis ​​externas, haveria problemas com minificadores.**
100100

101-
Besides, such code would be architecturally bad and prone to errors.
101+
Além disso, esse código seria arquitetonicamente ruim e sujeito a erros.
102102

103-
To pass something to a function, created as `new Function`, we should use its arguments.
103+
Para passar algo para uma função, criada como `new Function`, devemos usar seus argumentos.
104104

105-
## Summary
105+
## Resumo
106106

107-
The syntax:
107+
A sintaxe:
108108

109109
```js
110110
let func = new Function ([arg1, arg2, ...argN], functionBody);
111111
```
112112

113-
For historical reasons, arguments can also be given as a comma-separated list.
113+
Por razões históricas, os argumentos também podem ser apresentados como uma lista separada por vírgulas.
114114

115-
These three declarations mean the same:
115+
Estas três declarações significam o mesmo:
116116

117117
```js
118-
new Function('a', 'b', 'return a + b'); // basic syntax
119-
new Function('a,b', 'return a + b'); // comma-separated
120-
new Function('a , b', 'return a + b'); // comma-separated with spaces
118+
new Function('a', 'b', 'return a + b'); // sintaxe básica
119+
new Function('a,b', 'return a + b'); // separados por vírgula
120+
new Function('a , b', 'return a + b'); // separados por vírgula com espaços
121121
```
122122

123-
Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.
123+
Funções criadas com `new Function` têm `[[Environment]]` referenciando o ambiente lexical global, não o externo. Portanto, eles não podem usar variáveis ​​externas. Mas isso é realmente bom, porque nos protege contra erros. Passar parâmetros explicitamente é um método muito melhor do ponto de vista arquitetônico e não causa problemas com minificadores.

0 commit comments

Comments
 (0)