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 old "var"#166

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.4
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
218 changes: 109 additions & 109 deletions1-js/06-advanced-functions/04-var/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,287 +1,287 @@

#The old "var"
#Starý příkaz „var

```smart header="This article is for understanding old scripts"
The information in this article is useful for understanding old scripts.
```smart header="Tento článek slouží k pochopení starých skriptů"
Informace v tomto článku jsou užitečné k tomu, abyste porozuměli starým skriptům.

That's not how we write new code.
Není to způsob, jak psát nový kód.
```

In the very first chapter about [variables](info:variables), we mentioned three ways of variable declaration:
V úplně první kapitole o [proměnných](info:variables) jsme zmínili tři způsoby deklarace proměnných:

1. `let`
2. `const`
3. `var`

The `var`declaration is similar to`let`.Most of the time we can replace`let`by `var`or vice-versa and expect things to work:
Deklarace `var`je podobná`let`.Ve většině případů můžeme nahradit`let`za `var`nebo naopak a očekávat, že vše bude fungovat:

```js run
varmessage = "Hi";
alert(message); //Hi
varzpráva = "Ahoj";
alert(zpráva); //Ahoj
```

But internally`var`is a very different beast, that originates from very old times. It's generally not used in modern scripts, but still lurks in the old ones.
Vnitřně je však`var`velmi odlišná potvůrka, která pochází z dřívějších časů. V moderních skriptech se obvykle nepoužívá, ale ve starých stále číhá.

If you don't plan on meeting such scripts you may even skip this chapter or postpone it.
Pokud neplánujete se s takovými skripty setkat, můžete tuto kapitolu přeskočit nebo odložit na později.

On the other hand, it's important to understand differences when migrating old scripts from`var`to `let`,to avoid odd errors.
Naproti tomu, když převádíte staré skripty z`var`na `let`,je důležité porozumět rozdílům, abyste se vyhnuli podivným chybám.

##"var" has no block scope
##var“ nemá blokovou platnost

Variables, declared with `var`, are either function-scoped or global-scoped. They are visible through blocks.
Proměnné deklarované pomocí `var` mají rozsah platnosti buď funkční, nebo globální. Jsou viditelné i skrz bloky.

For instance:
Například:

```js run
if (true) {
var test = true; //use "var" instead of "let"
var test = true; //použijeme „var“ namísto „let
}

*!*
alert(test); // true,the variable lives after if
alert(test); // true,proměnná existuje i za if
*/!*
```

As `var`ignores code blocks, we've got a global variable `test`.
Protože `var`ignoruje kódové bloky, vytvořili jsme globální proměnnou `test`.

If we used`let test`instead of`var test`,then the variable would only be visible inside `if`:
Kdybychom použili`let test`namísto`var test`,pak by tato proměnná byla viditelná jen uvnitř `if`:

```js run
if (true) {
let test = true; //use "let"
let test = true; //použijeme „let
}

*!*
alert(test); // ReferenceError: testis not defined
alert(test); // ReferenceError: testnení definován
*/!*
```

The same thing for loops: `var`cannot be block- or loop-local:
Totéž platí pro cykly: `var`nemůže být lokální v bloku nebo ve smyčce:

```js run
for (var i = 0; i < 10; i++) {
varone = 1;
varjedna = 1;
// ...
}

*!*
alert(i); // 10,"i" is visible after loop, it's a global variable
alert(one); // 1,"one" is visible after loop, it's a global variable
alert(i); // 10,„i“ je viditelná i za cyklem, je to globální proměnná
alert(jedna); // 1,„jedna“ je viditelná i za cyklem, je to globální proměnná
*/!*
```

If a code block is inside a function, then `var`becomes a function-level variable:
Nachází-li se kódový blok uvnitř funkce, pak `var`deklaruje proměnnou na úrovni funkce:

```js run
functionsayHi() {
functionřekniAhoj() {
if (true) {
varphrase = "Hello";
varvěta = "Ahoj";
}

alert(phrase); //works
alert(věta); //funguje
}

sayHi();
alert(phrase); // ReferenceError:phrase is not defined
řekniAhoj();
alert(věta); // ReferenceError:věta není definována
```

As we can see, `var`pierces through`if`, `for`or other code blocks. That's because a long time ago in JavaScript, blocks had no Lexical Environments, and `var`is a remnant of that.
Jak vidíme, `var`se probije skrz`if`, `for`a jiné kódové bloky. Je to proto, že před dlouhou dobou bloky v JavaScriptu neměly lexikální prostředí a `var`je toho pozůstatkem.

##"var" tolerates redeclarations
##var“ toleruje opakované deklarace

If we declare the same variable with`let`twice in the same scope, that's an error:
Jestliže deklarujeme stejnou proměnnou pomocí`let`ve stejné oblasti dvakrát, nastane chyba:

```js run
letuser;
letuser; // SyntaxError: 'user' has already been declared
letuživatel;
letuživatel; // SyntaxError: 'uživatel' již byl deklarován
```

With `var`, we can redeclare a variable any number of times. If we use`var`with an already-declared variable, it's just ignored:
Pomocí `var` můžeme znovu deklarovat proměnnou, kolikrát chceme. Použijeme-li`var`s již deklarovanou proměnnou, bude ignorováno:

```js run
varuser = "Pete";
varuživatel = "Petr";

varuser = "John"; //this "var" does nothing (already declared)
// ...it doesn't trigger an error
varuživatel = "Jan"; //tento „var“ neudělá nic (proměnná je již deklarována)
// ...nevyvolá chybu

alert(user); //John
alert(uživatel); //Jan
```

##"var" variables can be declared below their use
##Pomocí „var“ můžeme proměnné deklarovat až po jejich použití

`var`declarations are processed when the function starts (or script starts for globals).
Deklarace`var`se zpracovávají, když se funkce spustí (nebo když se spustí skript, jsou-li globální).

In other words,`var`variables are defined from the beginning of the function, no matter where the definition is (assuming that the definition is not in the nested function).
Jinými slovy, proměnné deklarované pomocí`var`jsou definovány od začátku funkce bez ohledu na to, kde se jejich definice nachází (za předpokladu, že definice není uvnitř vnořené funkce).

So this code:
Takže tento kód:

```js run
functionsayHi() {
phrase = "Hello";
functionřekniAhoj() {
věta = "Ahoj";

alert(phrase);
alert(věta);

*!*
varphrase;
varvěta;
*/!*
}
sayHi();
řekniAhoj();
```

...Is technically the same as this (moved `varphrase` above):
...je technicky stejný jako tento (přesuneme `varvěta` nahoru):

```js run
functionsayHi() {
functionřekniAhoj() {
*!*
varphrase;
varvěta;
*/!*

phrase = "Hello";
věta = "Ahoj";

alert(phrase);
alert(věta);
}
sayHi();
řekniAhoj();
```

...Or even as this (remember, code blocks are ignored):
...Nebo i jako tento (pamatujte, že kódové bloky jsou ignorovány):

```js run
functionsayHi() {
phrase = "Hello"; // (*)
functionřekniAhoj() {
věta = "Ahoj"; // (*)

*!*
if (false) {
varphrase;
varvěta;
}
*/!*

alert(phrase);
alert(věta);
}
sayHi();
řekniAhoj();
```

People also call such behavior "hoisting" (raising),because all `var`are "hoisted" (raised) to the top of the function.
Takovému chování se někdy říká „stoupání“ (anglicky „hoisting“ nebo „raising),jelikož každý `var`„vystoupá“ („hoist“, „raise“) až k vrcholu funkce.

So in the example above, `if (false)`branch never executes, but that doesn't matter. The `var`inside it is processed in the beginning of the function, so at the moment of `(*)`the variable exists.
V uvedeném příkladu se větev `if (false)`nikdy nespustí, ale na tom nezáleží. Příkaz `var`uvnitř se zpracuje na začátku funkce, takže v okamžiku provedení řádku `(*)`proměnná existuje.

**Declarations are hoisted, but assignments are not.**
**Deklarace stoupají, ale přiřazení ne.**

That's best demonstrated with an example:
Nejlépe to uvidíme na příkladu:

```js run
functionsayHi() {
alert(phrase);
functionřekniAhoj() {
alert(věta);

*!*
varphrase = "Hello";
varvěta = "Ahoj";
*/!*
}

sayHi();
řekniAhoj();
```

The line`varphrase = "Hello"`has two actions in it:
Řádek`varvěta = "Ahoj"`má v sobě dvě akce:

1.Variable declaration `var`
2.Variable assignment `=`.
1.Deklaraci proměnné `var`.
2.Přiřazení proměnné `=`.

The declaration is processed at the start of function execution ("hoisted"),but the assignment always works at the place where it appears. So the code works essentially like this:
Deklarace se vykonává na začátku spuštění funkce („stoupání“),ale přiřazení se provede vždy na místě, na němž se objevilo. Kód tedy funguje v zásadě následovně:

```js run
functionsayHi() {
functionřekniAhoj() {
*!*
varphrase; //declaration works at the start...
varvěta; //deklarace se provede na začátku...
*/!*

alert(phrase); // undefined
alert(věta); // undefined

*!*
phrase = "Hello"; // ...assignment -when the execution reaches it.
věta = "Ahoj"; // ...přiřazení -když se běh dostane k němu.
*/!*
}

sayHi();
řekniAhoj();
```

Because all`var`declarations are processed at the function start, we can reference them at any place. But variables are undefined until the assignments.
Protože všechny deklarace`var`se zpracovávají na začátku funkce, můžeme je uvádět kdekoli. Ale proměnné jsou až do přiřazení nedefinované.

In both examples above,`alert`runs without an error, because the variable `phrase` exists. But its value is not yet assigned, so it shows `undefined`.
V obou uvedených příkladech se`alert`spustí bez chyby, protože proměnná `věta` existuje. Ale ještě jí není přiřazena hodnota, takže se zobrazí `undefined`.

## IIFE

In the past, as there was only`var`, and it has no block-level visibility, programmers invented a way to emulate it. What they did was called "immediately-invoked function expressions" (abbreviated asIIFE).
V minulosti, kdy bylo jenom`var` a neexistovala viditelnost na úrovni bloku, programátoři vymysleli způsob, jak ji emulovat. To, co vynalezli, bylo nazváno „okamžitě volané funkční výrazy“ („immediately-invoked function expressions“), zkráceněIIFE.

That's not something we should use nowadays, but you can find them in old scripts.
Není to nic, co bychom měli používat v současnosti, ale ve starých skriptech je stále můžete najít.

AnIIFElooks like this:
IIFEvypadá následovně:

```js run
(function() {

varmessage = "Hello";
varzpráva = "Ahoj";

alert(message); //Hello
alert(zpráva); //Ahoj

})();
```

Here, a Function Expression is created and immediately called. So the code executes right away and has its own private variables.
Zde se vytvoří a okamžitě zavolá funkční výraz. Kód se tedy okamžitě spustí a má své vlastní soukromé proměnné.

The Function Expression is wrapped with parenthesis`(function {...})`,because when JavaScript engine encounters `"function"` in the main code, it understands it as the start of a Function Declaration. But a Function Declaration must have a name, so this kind of code will give an error:
Funkční výraz je uzavřen do závorek`(function {...})`,protože když motor JavaScriptu narazí v hlavním kódu na `„function“`, chápe to jako začátek deklarace funkce. Avšak deklarace funkce musí obsahovat název, takže tento kód vyvolá chybu:

```js run
//Tries to declare and immediately call a function
function() { // <-- SyntaxError:Function statements require a function name
//Snaží se deklarovat a okamžitě zavolat funkci
function() { // <-- SyntaxError:Deklarace funkce vyžaduje název funkce

varmessage = "Hello";
varzpráva = "Ahoj";

alert(message); //Hello
alert(zpráva); //Ahoj

}();
```

Even if we say: "okay, let's add a name", that won't work, as JavaScriptdoes not allow Function Declarations to be called immediately:
I kdybychom si řekli: „dobře, tak přidáme název“, nebude to fungovat, protože JavaScriptneumožňuje, aby byla deklarace funkce okamžitě volána:

```js run
//syntax error because of parentheses below
functiongo() {
//závorky níže způsobí syntaktickou chybu
functionjdi() {

}(); // <--can't call Function Declaration immediately
}(); // <--deklaraci funkce nemůžeme okamžitě volat
```

So, the parentheses around the function is a trick to show JavaScript that the function is created in the context of another expression, and hence it's a Function Expression: it needs no name and can be called immediately.
Závorky kolem funkce jsou tedy trik, jak ukázat JavaScriptu, že funkce je vytvořena v kontextu jiného výrazu, a proto je to funkční výraz: nemusí mít název a může být okamžitě zavolán.

There exist other ways besides parentheses to tell JavaScript that we mean a Function Expression:
Kromě závorek existují i jiné způsoby, jak oznámit JavaScriptu, že máme na mysli funkční výraz:

```js run
//Ways to create IIFE
//Způsoby vytvoření IIFE

*!*(*/!*function() {
alert("Parentheses around the function");
alert("Závorky okolo funkce");
}*!*)*/!*();

*!*(*/!*function() {
alert("Parentheses around the whole thing");
alert("Závorky okolo toho všeho");
}()*!*)*/!*;

*!*!*/!*function() {
alert("BitwiseNOToperator starts the expression");
alert("Bitový operátorNOTzahajuje výraz");
}();

*!*+*/!*function() {
alert("Unary plusstarts the expression");
alert("Unární pluszahajuje výraz");
}();
```

In all the above cases we declare aFunction Expression and run it immediately. Let's note again: nowadays there's no reason to write such code.
Ve všech uvedených případech deklarujeme funkční výraz aokamžitě jej zavoláme. Znovu opakujeme, že v dnešní době není důvod takový kód psát.

##Summary
##Shrnutí

There are two main differences of`var`compared to`let/const`:
Mezi`var`a`let/const` existují dva hlavní rozdíly:

1. `var`variables have no block scope, their visibility is scoped to current function, or global, if declared outside function.
2. `var`declarations are processed at function start (script start for globals).
1.Proměnné deklarované pomocí`var`nemají blokovou platnost a oblast jejich viditelnosti je celá aktuální funkce. Jsou-li deklarovány mimo funkci, jsou globální.
2.Deklarace`var`se zpracovávají na začátku funkce (globální deklarace na začátku skriptu).

There's one more very minor difference related to the global object, that we'll cover in the next chapter.
Existuje ještě jeden velmi drobný rozdíl vztahující se ke globálnímu objektu, který probereme v příští kapitole.

These differences make`var`worse than `let` most of the time. Block-level variables is such a great thing. That's why `let` was introduced in the standard long ago, and is now amajor way (along with `const`) to declare a variable.
Kvůli těmto rozdílům je`var`ve většině případů horší než `let`. Proměnné na úrovni bloku jsou vynikající věc. To je důvod, proč bylo do standardu již před dlouhou dobou zavedeno `let` anyní je hlavním způsobem (spolu s `const`), jak deklarovat proměnné.

[8]ページ先頭

©2009-2025 Movatter.jp