Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The "new Function" syntax#169

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 1 commit intojavascript-tutorial:masterfromotmon76:1.6.7
Jun 3, 2025
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 53 additions & 53 deletions1-js/06-advanced-functions/07-new-function/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,123 +1,123 @@

#The "new Function" syntax
#Syntaxe „new Function

There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
Existuje ještě jeden způsob, jak vytvořit funkci. Používá se jen zřídka, ale někdy nemáme jinou možnost.

##Syntax
##Syntaxe

The syntax for creating a function:
Syntaxe vytvoření funkce:

```js
letfunc = new Function ([arg1, arg2, ...argN],functionBody);
letfunkce = new Function ([arg1, arg2, ...argN],těloFunkce);
```

The function is created with the arguments`arg1...argN`and the given `functionBody`.
Funkce je vytvořena s argumenty`arg1...argN`a zadaným tělem `těloFunkce`.

It's easier to understand by looking at an example. Here's a function with two arguments:
Je snadnější tomu porozumět, když se podíváme na příklad. Toto je funkce se dvěma argumenty:

```js run
letsum = new Function('a', 'b', 'return a + b');
letsečti = new Function('a', 'b', 'return a + b');

alert(sum(1, 2) ); // 3
alert(sečti(1, 2) ); // 3
```

And here there's a function without arguments, with only the function body:
A zde je funkce bez argumentů, jenom s tělem:

```js run
letsayHi = new Function('alert("Hello")');
letřekniAhoj = new Function('alert("Ahoj")');

sayHi(); //Hello
řekniAhoj(); //Ahoj
```

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.
Hlavní rozdíl oproti ostatním způsobům, jaké jsme viděli, je, že funkce je vytvořena doslovně z řetězce, který je předán za běhu skriptu.

All previous declarations required us, programmers, to write the function code in the script.
Všechny předchozí deklarace po nás programátorech požadovaly, abychom zapsali kód funkce do skriptu.

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:
Avšak `new Function`umožňuje převést libovolný řetězec na funkci. Například můžeme získat novou funkci ze serveru a pak ji spustit:

```js
letstr = ...receive the code from a server dynamically ...
letřetězec = ...dynamické získání kódu ze serveru ...

letfunc = new Function(str);
func();
letfunkce = new Function(řetězec);
funkce();
```

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.
Používá se jen ve velmi specifických případech, například když získáme kód ze serveru, nebo když chceme dynamicky kompilovat funkci ze šablony ve složitých webových aplikacích.

##Closure
##Uzávěr

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>).
Funkce si zpravidla pamatuje, kde se zrodila, ve speciální vlastnosti`[[Environment]]`.Ta se odkazuje na lexikální prostředí, z něhož byla funkce vytvořena (probrali jsme to v kapitole <info:closure>).

But when a function is created using`new Function`,its`[[Environment]]`is set to reference not the current Lexical Environment, but the global one.
Když je však funkce vytvořena pomocí`new Function`,její vlastnost`[[Environment]]`se nenastaví na odkaz na aktuální lexikální prostředí, ale na globální.

So, such function doesn't have access to outer variables, only to the global ones.
Taková funkce tedy nemá přístup k vnějším proměnným, jedině ke globálním.

```js run
functiongetFunc() {
letvalue = "test";
functionvraťFunkci() {
lethodnota = "test";

*!*
letfunc = new Function('alert(value)');
letfunkce = new Function('alert(hodnota)');
*/!*

returnfunc;
returnfunkce;
}

getFunc()(); //error: value is not defined
vraťFunkci()(); //chyba: hodnota není definována
```

Compare it with the regular behavior:
Porovnejte si to s běžným chováním:

```js run
functiongetFunc() {
letvalue = "test";
functionvraťFunkci() {
lethodnota = "test";

*!*
letfunc = function() { alert(value); };
letfunkce = function() { alert(hodnota); };
*/!*

returnfunc;
returnfunkce;
}

getFunc()(); // *!*"test"*/!*,from the Lexical Environment of getFunc
vraťFunkci()(); // *!*"test"*/!*,z lexikálního prostředí funkce vraťFunkci
```

This special feature of`new Function`looks strange, but appears very useful in practice.
Tato speciální vlastnost`new Function`vypadá zvláštně, ale v praxi se ukazuje být velmi užitečná.

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.
Představme si, že musíme vytvořit funkci z řetězce. Kód této funkce není znám v době psaní skriptu (to je důvod, proč nepoužijeme obvyklou funkci),ale bude znám při jeho běhu. Můžeme jej získat ze serveru nebo z jiného zdroje.

Our new function needs to interact with the main script.
Naše nová funkce musí interagovat s hlavním skriptem.

What if it could access the outer variables?
Co kdyby mohla přistupovat k vnějším proměnným?

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.
Problém je v tom, že předtím, než je JavaScriptový skript zveřejněn k používání, je zkomprimován *minifikátorem* --speciálním programem, který zkrátí kód tím, že odstraní komentáře, přebytečné mezery a--co je důležité, přejmenuje názvy lokálních proměnných na kratší.

For instance, if a function has`letuserName`,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 adumb find-and-replace.
Například jestliže funkce obsahuje`letuživatelskéJméno`,minifikátor je nahradí za `let a` (nebo jiné písmeno, které ještě není použito) a učiní tak všude. To je obvykle bezpečné, jelikož proměnná je lokální a nic mimo funkci k ní nemůže přistupovat. A uvnitř funkce minifikátor nahradí tuto proměnnou všude, kde je uvedena. Minifikátory jsou chytré, analyzují strukturu kódu, takže nic nerozbíjejí. Není to jen tupé najdi anahraď.

So if `new Function`had access to outer variables, it would be unable to find renamed `userName`.
Kdyby tedy `new Function`měla přístup k vnějším proměnným, nedokázala by najít přejmenované `uživatelskéJméno`.

**If `new Function`had access to outer variables, it would have problems with minifiers.**
**Kdyby `new Function`měla přístup k vnějším proměnným, měla by problémy s minifikátory.**

Besides, such code would be architecturally bad and prone to errors.
Navíc by takový kód byl architektonicky špatný a náchylný k chybám.

To pass something to a function, created as `new Function`,we should use its arguments.
K tomu, abychom něco předali funkci vytvořené pomocí `new Function`,bychom měli používat její argumenty.

##Summary
##Shrnutí

The syntax:
Syntaxe:

```js
letfunc = new Function ([arg1, arg2, ...argN],functionBody);
letfunkce = new Function ([arg1, arg2, ...argN],těloFunkce);
```

For historical reasons, arguments can also be given as a comma-separated list.
Z historických důvodů můžeme argumenty uvést i jako seznam oddělený čárkou.

These three declarations mean the same:
Tyto tři deklarace znamenají totéž:

```js
new Function('a', 'b', 'return a + b'); //basic syntax
new Function('a,b', 'return a + b'); //comma-separated
new Function('a , b', 'return a + b'); //comma-separated with spaces
new Function('a', 'b', 'return a + b'); //základní syntaxe
new Function('a,b', 'return a + b'); //oddělené čárkou
new Function('a , b', 'return a + b'); //oddělené čárkou s mezerami
```

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.
Vlastnost `[[Environment]]` funkcí vytvořených pomocí`new Function` se odkazuje na globální lexikální prostředí, ne na vnější. Proto tyto funkce nemohou používat vnější proměnné. To je však ve skutečnosti dobře, protože nás to ochraňuje před chybami. Výslovné předávání parametrů je architektonicky mnohem lepší způsob a nezpůsobuje problémy s minifikátory.

[8]ページ先頭

©2009-2025 Movatter.jp