Repository navigation
Eval: run a code string #487
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,11 +1,11 @@ | ||||||
| Let's use `eval` to calculate the maths expression: | ||||||
| Vamos usar `eval` para calcular a expressão matemática: | ||||||
|
|
||||||
| ```js demo run | ||||||
| let expr = prompt("Type an arithmetic expression?", '2*3+2'); | ||||||
| let expr = prompt("Digite uma expressão aritmética?", '2*3+2'); | ||||||
|
|
||||||
| alert( eval(expr) ); | ||||||
| ``` | ||||||
|
|
||||||
| The user can input any text or code though. | ||||||
| Porém, o usuário pode digitar qualquer texto ou código. | ||||||
|
|
||||||
| To make things safe, and limit it to arithmetics only, we can check the `expr` using a [regular expression](info:regular-expressions), so that it only may contain digits and operators. | ||||||
| Para deixar as coisas seguras, e limitar só a aritmética, podemos verificar `expr` usando uma [expressão regular](info:regular-expressions), de forma que ela só possa conter dígitos e operadores. | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tradução muda o sentido: "limitar só a aritmética" se lê como "restringir apenas a aritmética", o oposto do original ("limit it to arithmetics only"). Sugestão:
Suggested change
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,25 @@ | ||
| # Eval: run a code string | ||
| # Eval: executa uma string de código | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Título: "executa" (3ª pessoa) soa como frase descritiva, não título. Outros títulos do tutorial usam substantivo/infinitivo. Sugestão: |
||
|
|
||
| The built-in `eval` function allows to execute a string of code. | ||
| A função nativa `eval` permite executar uma string de código. | ||
|
|
||
| The syntax is: | ||
| A sintaxe é: | ||
|
|
||
| ```js | ||
| let result = eval(code); | ||
| ``` | ||
|
|
||
| For example: | ||
| Por exemplo: | ||
|
|
||
| ```js run | ||
| let code = 'alert("Hello")'; | ||
| eval(code); // Hello | ||
| ``` | ||
|
|
||
| A string of code may be long, contain line breaks, function declarations, variables and so on. | ||
| Uma string de código pode ser longa, conter quebras de linha, declarações de função, variáveis e assim por diante. | ||
|
|
||
| The result of `eval` is the result of the last statement. | ||
| O resultado de `eval` é o resultado da última instrução. | ||
|
|
||
| For example: | ||
| Por exemplo: | ||
| ```js run | ||
| let value = eval('1+1'); | ||
| alert(value); // 2 | ||
|
|
@@ -30,7 +30,7 @@ let value = eval('let i = 0; ++i'); | |
| alert(value); // 1 | ||
| ``` | ||
|
|
||
| The eval'ed code is executed in the current lexical environment, so it can see outer variables: | ||
| O código executado pelo eval roda no Ambiente Léxico atual, então ele consegue ver as variáveis externas: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Terminologia inconsistente: "Ambiente Léxico" (também nas linhas 57 e 68) diverge de "Ambiente Lexical", usado em |
||
|
|
||
| ```js run no-beautify | ||
| let a = 1; | ||
|
|
@@ -46,69 +46,69 @@ function f() { | |
| f(); | ||
| ``` | ||
|
|
||
| It can change outer variables as well: | ||
| Ele também consegue mudar variáveis externas: | ||
|
|
||
| ```js untrusted refresh run | ||
| let x = 5; | ||
| eval("x = 10"); | ||
| alert(x); // 10, value modified | ||
| alert(x); // 10, valor modificado | ||
| ``` | ||
|
|
||
| In strict mode, `eval` has its own lexical environment. So functions and variables, declared inside eval, are not visible outside: | ||
| No modo estrito, `eval` tem seu próprio Ambiente Léxico. Então funções e variáveis declaradas dentro do eval não são visíveis fora: | ||
|
|
||
| ```js untrusted refresh run | ||
| // reminder: 'use strict' is enabled in runnable examples by default | ||
| // lembrete: 'use strict' é ativado por padrão em exemplos executáveis | ||
|
|
||
| eval("let x = 5; function f() {}"); | ||
|
|
||
| alert(typeof x); // undefined (no such variable) | ||
| // function f is also not visible | ||
| alert(typeof x); // undefined (essa variável não existe) | ||
| // a função f também não é visível | ||
| ``` | ||
|
|
||
| Without `use strict`, `eval` doesn't have its own lexical environment, so we would see `x` and `f` outside. | ||
| Sem `use strict`, `eval` não tem seu próprio Ambiente Léxico, então veríamos `x` e `f` fora. | ||
|
|
||
| ## Using "eval" | ||
| ## Usando o "eval" | ||
|
|
||
| In modern programming `eval` is used very sparingly. It's often said that "eval is evil". | ||
| Na programação moderna, o `eval` é usado bem raramente. Costuma-se dizer que "eval is evil" ("eval é maligno"). | ||
|
|
||
| The reason is simple: long, long time ago JavaScript was a much weaker language, many things could only be done with `eval`. But that time passed a decade ago. | ||
| O motivo é simples: há muito, muito tempo, o JavaScript era uma linguagem bem mais fraca, e muitas coisas só podiam ser feitas com `eval`. Mas essa época passou há uma década. | ||
|
|
||
| Right now, there's almost no reason to use `eval`. If someone is using it, there's a good chance they can replace it with a modern language construct or a [JavaScript Module](info:modules). | ||
| Hoje em dia, quase não há motivo para usar `eval`. Se alguém está usando, há uma boa chance de que consiga substituir por uma construção moderna da linguagem ou um [Módulo JavaScript](info:modules). | ||
|
|
||
| Please note that its ability to access outer variables has side-effects. | ||
| Observe que sua capacidade de acessar variáveis externas tem efeitos colaterais. | ||
|
|
||
| Code minifiers (tools used before JS gets to production, to compress it) rename local variables into shorter ones (like `a`, `b` etc) to make the code smaller. That's usually safe, but not if `eval` is used, as local variables may be accessed from eval'ed code string. So minifiers don't do that renaming for all variables potentially visible from `eval`. That negatively affects code compression ratio. | ||
| Minificadores de código (ferramentas usadas antes do JS ir pra produção, pra comprimi-lo) renomeiam variáveis locais para nomes mais curtos (tipo `a`, `b` etc.) pra deixar o código menor. Isso normalmente é seguro, mas não quando `eval` é usado, já que variáveis locais podem ser acessadas a partir da string de código do eval. Então os minificadores não fazem essa renomeação para todas as variáveis potencialmente visíveis a partir do `eval`. Isso afeta negativamente a taxa de compressão do código. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Registro informal ("pra produção", "pra comprimi-lo", "tipo |
||
|
|
||
| Using outer local variables inside `eval` is also considered a bad programming practice, as it makes maintaining the code more difficult. | ||
| Usar variáveis locais externas dentro do `eval` também é considerado uma má prática de programação, já que torna a manutenção do código mais difícil. | ||
|
|
||
| There are two ways how to be totally safe from such problems. | ||
| Existem duas formas de ficar totalmente a salvo desses problemas. | ||
|
|
||
| **If eval'ed code doesn't use outer variables, please call `eval` as `window.eval(...)`:** | ||
| **Se o código executado pelo eval não usa variáveis externas, chame `eval` como `window.eval(...)`:** | ||
|
|
||
| This way the code is executed in the global scope: | ||
| Dessa forma, o código é executado no escopo global: | ||
|
|
||
| ```js untrusted refresh run | ||
| let x = 1; | ||
| { | ||
| let x = 5; | ||
| window.eval('alert(x)'); // 1 (global variable) | ||
| window.eval('alert(x)'); // 1 (variável global) | ||
| } | ||
| ``` | ||
|
|
||
| **If eval'ed code needs local variables, change `eval` to `new Function` and pass them as arguments:** | ||
| **Se o código executado pelo eval precisa de variáveis locais, troque `eval` por `new Function` e as passe como argumentos:** | ||
|
|
||
| ```js run | ||
| let f = new Function('a', 'alert(a)'); | ||
|
|
||
| f(5); // 5 | ||
| ``` | ||
|
|
||
| The `new Function` construct is explained in the chapter <info:new-function>. It creates a function from a string, also in the global scope. So it can't see local variables. But it's so much clearer to pass them explicitly as arguments, like in the example above. | ||
| A construção `new Function` é explicada no capítulo <info:new-function>. Ela cria uma função a partir de uma string, também no escopo global. Então ela não consegue ver variáveis locais. Mas é muito mais claro passá-las explicitamente como argumentos, como no exemplo acima. | ||
|
|
||
| ## Summary | ||
| ## Resumo | ||
|
|
||
| A call to `eval(code)` runs the string of code and returns the result of the last statement. | ||
| - Rarely used in modern JavaScript, as there's usually no need. | ||
| - Can access outer local variables. That's considered bad practice. | ||
| - Instead, to `eval` the code in the global scope, use `window.eval(code)`. | ||
| - Or, if your code needs some data from the outer scope, use `new Function` and pass it as arguments. | ||
| Uma chamada a `eval(code)` roda a string de código e retorna o resultado da última instrução. | ||
| - Raramente usado no JavaScript moderno, já que normalmente não há necessidade. | ||
| - Pode acessar variáveis locais externas. Isso é considerado má prática. | ||
| - Em vez disso, para executar o `eval` do código no escopo global, use `window.eval(code)`. | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Construção truncada: "executar o |
||
| - Ou, se seu código precisa de alguns dados do escopo externo, use `new Function` e os passe como argumentos. | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pergunta com imperativo: "Digite uma expressão aritmética?" — o "?" herdado do original fica estranho em português. Sugestão:
prompt("Digite uma expressão aritmética:", '2*3+2').