You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
The first kind is *data properties*.We already know how to work with them. All properties that we've been using until now were data properties.
První druh jsou *datové vlastnosti*.S nimi už pracovat umíme. Všechny vlastnosti, které jsme až doposud používali, byly datové vlastnosti.
The second type of property is something new. It's an *accessor property*.They are essentially functions that execute on getting and setting avalue, but look like regular properties to an external code.
Druhý druh vlastností je něco nového. Jsou to *přístupové vlastnosti*.Jsou to v zásadě funkce, které se spustí při načítání anastavování hodnoty, ale v externím kódu vypadají jako běžné vlastnosti.
##Getters and setters
##Gettery a settery
Accessor properties are represented by "getter" and "setter" methods. In an object literal they are denoted by`get`and `set`:
Přístupové vlastnosti jsou představovány metodami nazývanými „getter“ a „setter“. V objektovém literálu jsou označeny`get`a `set`:
```js
let obj = {
*!*getpropName()*/!* {
// getter,the code executed on gettingobj.propName
*!*getnázevVlastnosti()*/!* {
// getter,kód spuštěný při načítáníobj.názevVlastnosti
},
*!*setpropName(value)*/!* {
// setter,the code executed on settingobj.propName =value
*!*setnázevVlastnosti(hodnota)*/!* {
// setter,kód spuštěný při nastavováníobj.názevVlastnosti =hodnota
}
};
```
The getter works when`obj.propName` is read, thesetter-- when it is assigned.
Getter se spustí, když je vlastnost`obj.názevVlastnosti` načítána,setterse spustí, když je měněna.
For instance, we have a `user` object with `name` and `surname`:
Například máme objekt `uživatel` s vlastnostmi `jméno` a `příjmení`:
```js
letuser = {
name: "John",
surname: "Smith"
letuživatel = {
jméno: "Jan",
příjmení: "Novák"
};
```
Now we want to add a `fullName` property, that should be `"John Smith"`.Of course, we don't want to copy-paste existing information, so we can implement it as an accessor:
Nyní chceme přidat vlastnost `celéJméno`, která by měla být `"Jan Novák"`.Samozřejmě nechceme kopírovat a vkládat existující informaci, a tak ji můžeme implementovat jako přístupovou:
```js run
letuser = {
name: "John",
surname: "Smith",
letuživatel = {
jméno: "Jan",
příjmení: "Novák",
*!*
getfullName() {
return `${this.name} ${this.surname}`;
getceléJméno() {
return `${this.jméno} ${this.příjmení}`;
}
*/!*
};
*!*
alert(user.fullName); //John Smith
alert(uživatel.celéJméno); //Jan Novák
*/!*
```
From the outside, an accessor property looks like a regular one. That's the idea of accessor properties. We don't *call* `user.fullName` as a function, we *read* it normally: thegetterruns behind the scenes.
Zvenčí se přístupová vlastnost jeví jako obyčejná. To je myšlenka přístupových vlastností. *Nevoláme* `uživatel.celéJméno` jako funkci, ale normálně ji *přečteme*:getterse spustí za scénou.
As of now, `fullName` has only agetter.If we attempt to assign `user.fullName=`,there will be an error:
Dosud má `celéJméno` jengetter.Jestliže se pokusíme přiřadit `uživatel.celéJméno=`,nastane chyba:
```js run
letuser = {
getfullName() {
letuživatel = {
getceléJméno() {
return `...`;
}
};
*!*
user.fullName = "Test"; //Error (property has only a getter)
uživatel.celéJméno = "Test"; //Chyba (vlastnost má jen getter)
*/!*
```
Let's fix it by adding a setter for `user.fullName`:
Opravme ji přidáním setteru pro `uživatel.celéJméno`:
```js run
letuser = {
name: "John",
surname: "Smith",
letuživatel = {
jméno: "Jan",
příjmení: "Novák",
getfullName() {
return `${this.name} ${this.surname}`;
getceléJméno() {
return `${this.jméno} ${this.příjmení}`;
},
*!*
setfullName(value) {
[this.name, this.surname] =value.split(" ");
setceléJméno(hodnota) {
[this.jméno, this.příjmení] =hodnota.split(" ");
}
*/!*
};
//set fullName is executed with the given value.
user.fullName = "Alice Cooper";
//nastavení vlastnosti celéJméno se spustí se zadanou hodnotou.
uživatel.celéJméno = "Alice Cooper";
alert(user.name); // Alice
alert(user.surname); // Cooper
alert(uživatel.jméno); // Alice
alert(uživatel.příjmení); // Cooper
```
As the result, we have a "virtual" property `fullName`.It is readable and writable.
Výsledkem je, že máme „virtuální“ vlastnost `celéJméno`.Lze ji číst i do ní zapisovat.
##Accessor descriptors
##Deskriptory přístupových vlastností
Descriptors for accessor properties are different from those for data properties.
Deskriptory přístupových vlastností se liší od deskriptorů datových vlastností.
For accessor properties, there is no `value`or `writable`,but instead there are`get`and `set` functions.
U přístupových vlastností v nich nejsou `value`nebo `writable`,ale místo nich tam jsou funkce`get`a `set`.
That is, an accessor descriptor may have:
To znamená, že přístupový deskriptor může mít:
- **`get`** --a function without arguments, that works when a property is read,
- **`set`** --a function with one argument, that is called when the property is set,
- **`enumerable`** --same as for data properties,
- **`configurable`** --same as for data properties.
- **`get`** --funkce bez argumentů, která se spustí při čtení vlastnosti,
- **`set`** --funkce s jedním argumentem, která je volána, když se vlastnost nastavuje,
- **`enumerable`** --totéž jako u datových vlastností,
- **`configurable`** --totéž jako u datových vlastností.
For instance, to create an accessor `fullName` with`defineProperty`,we can pass a descriptor with`get`and `set`:
Například chceme-li vytvořit přístupovou vlastnost `celéJméno` pomocí metody`defineProperty`,můžeme předat deskriptor s`get`a `set`:
Getters/setters can be used as wrappers over "real" property values to gain more control over operations with them.
Gettery a settery můžeme používat jako obaly nad „skutečnými“ hodnotami vlastností, abychom nad operacemi s nimi získali větší kontrolu.
For instance, if we want to forbid too short names for `user`, we can have asetter `name` and keep the value in a separate property `_name`:
Například jestliže chceme v objektu `uživatel` zakázat příliš krátká jména, můžeme mítsetter `jméno` a udržovat hodnotu v oddělené vlastnosti `_jméno`:
```js run
letuser = {
getname() {
return this._name;
letuživatel = {
getjméno() {
return this._jméno;
},
setname(value) {
if (value.length < 4) {
alert("Name is too short, need at least 4characters");
setjméno(hodnota) {
if (hodnota.length < 4) {
alert("Jméno je příliš krátké, musí mít alespoň 4znaky");
return;
}
this._name =value;
this._jméno =hodnota;
}
};
user.name = "Pete";
alert(user.name); //Pete
uživatel.jméno = "Petr";
alert(uživatel.jméno); //Petr
user.name = ""; //Name is too short...
uživatel.jméno = ""; //Jméno je příliš krátké...
```
So, the name is stored in `_name` property, and the access is done via getterand setter.
Jméno je tedy uloženo ve vlastnosti `_jméno` a přístup k němu se děje přes gettera setter.
Technically, external code is able to access the name directly by using `user._name`.But there is a widely known convention that properties starting with an underscore`"_"`are internal and should not be touched from outside the object.
Technicky může externí kód přistupovat přímo ke jménu pomocí `uživatel._jméno`.Podle široce rozšířené konvence však vlastnosti začínající podtržítkem`"_"`jsou interní a nemělo by se na ně sahat zvnějšku objektu.
## Používání pro kompatibilitu
## Using for compatibility
Jedním z vynikajících využití přístupových vlastností je, že umožňují kdykoli převzít kontrolu nad „obyčejnou“ datovou vlastností tím, že ji nahradíme getterem a setterem a vylepšíme její chování.
One of the great uses of accessors is that they allow to take control over a "regular" data property at any moment by replacing it with a getter and a setter and tweak its behavior.
Imagine we started implementing user objects using data properties `name` and `age`:
Představme si, že jsme začali implementovat objekty uživatelů s použitím datových vlastností `jméno` a `věk`:
```js
functionUser(name, age) {
this.name =name;
this.age =age;
functionUživatel(jméno, věk) {
this.jméno =jméno;
this.věk =věk;
}
letjohn = newUser("John", 25);
letjan = newUživatel("Jan", 25);
alert(john.age ); // 25
alert(jan.věk ); // 25
```
...But sooner or later, things may change. Instead of `age` we may decide to store `birthday`,because it's more precise and convenient:
...Dříve nebo později se to však může změnit. Místo vlastnosti `věk` se můžeme rozhodnout ukládat `datumNarození`,protože je to přesnější a vhodnější:
```js
functionUser(name, birthday) {
this.name =name;
this.birthday =birthday;
functionUživatel(jméno, datumNarození) {
this.jméno =jméno;
this.datumNarození =datumNarození;
}
letjohn = newUser("John", new Date(1992, 6, 1));
letjan = newUživatel("Jan", new Date(1992, 6, 1));
```
Now what to do with the old code that still uses `age` property?
Co teď uděláme se starým kódem, který stále používá vlastnost `věk`?
We can try to find all such places and fix them, but that takes time and can be hardtodo if that code is used by many other people. And besides, `age` is a nice thing to have in `user`,right?
Můžeme se pokusit všechna taková místa najít a opravit, ale to nám zabere čas a můžetobýt těžko proveditelné, jestliže tento kód používá mnoho dalších lidí. A kromě toho je hezké mít `věk` v objektu `uživatel`,ne?
Let's keep it.
Necháme si ho.
Adding a getter for `age` solves the problem:
Problém vyřeší přidání getteru pro `věk`:
```js run no-beautify
functionUser(name, birthday) {
this.name =name;
this.birthday =birthday;
functionUživatel(jméno, datumNarození) {
this.jméno =jméno;
this.datumNarození =datumNarození;
*!*
//age is calculated from the current date and birthday
Object.defineProperty(this, "age", {
//věk se vypočítá z dnešního data a z data narození
letjan = newUživatel("Jan", new Date(1992, 6, 1));
alert(john.birthday ); //birthday is available
alert(john.age ); // ...as well as the age
alert(jan.datumNarození ); //datumNarození je k dispozici
alert(jan.věk ); // ...stejně jako věk
```
Now the old code works too and we've got a nice additional property.
Nyní bude fungovat i starý kód a navíc jsme získali další pěknou vlastnost.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.