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
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
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 `instanceof`operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
Operátor `instanceof`umožňuje ověřit, zda objekt patří do určité třídy. Bere v úvahu i dědičnost.
Such a check may be necessary in many cases. For example, it can be used for building a *polymorphic* function, the one that treats arguments differently depending on their type.
Toto ověření může být zapotřebí v mnoha případech. Například může být použito k vytvoření *polymorfní* funkce, takové, která zachází se svými argumenty různě v závislosti na jejich typu.
##The instanceof operator [#ref-instanceof]
##Operátor instanceof [#ref-instanceof]
The syntax is:
Syntaxe je:
```js
obj instanceofClass
obj instanceofTřída
```
It returns`true` if `obj`belongs to the `Class` or a class inheriting from it.
Vrací`true`, jestliže `obj`patří do třídy `Třída` nebo do třídy, která je z ní zděděna.
For instance:
Například:
```js run
classRabbit {}
letrabbit = newRabbit();
classKrálík {}
letkrálík = newKrálík();
//is it an object of Rabbit class?
//je to objekt třídy Králík?
*!*
alert(rabbit instanceofRabbit ); // true
alert(králík instanceofKrálík ); // true
*/!*
```
It also works with constructor functions:
Funguje to i pro konstruktory:
```js run
*!*
//instead of class
functionRabbit() {}
//namísto třídy
functionKrálík() {}
*/!*
alert( newRabbit() instanceofRabbit ); // true
alert( newKrálík() instanceofKrálík ); // true
```
...And with built-in classes like `Array`:
...A pro zabudované třídy jako `Array`:
```js run
letarr = [1, 2, 3];
alert(arr instanceof Array ); // true
alert(arr instanceof Object ); // true
letpole = [1, 2, 3];
alert(pole instanceof Array ); // true
alert(pole instanceof Object ); // true
```
Please note that `arr` also belongs to the `Object` class. That's because`Array`prototypically inherits from `Object`.
Prosíme všimněte si, že `pole` patří i do třídy `Object`. Je to proto, že třída`Array`je prototypově zděděna z třídy `Object`.
Normally, `instanceof`examines the prototype chain for the check. We can also set a custom logic in the static method `Symbol.hasInstance`.
Normálně `instanceof`při ověřování prozkoumává prototypový řetězec. Můžeme si však také nastavit vlastní logiku ve statické metodě `Symbol.hasInstance`.
The algorithm of`obj instanceofClass` works roughly as follows:
Algoritmus operátoru`obj instanceofTřída` funguje zhruba následovně:
1.If there's a static method`Symbol.hasInstance`,then just call it: `Class[Symbol.hasInstance](obj)`.It should return either`true` or `false`,and we're done. That's how we can customize the behavior of`instanceof`.
1.Pokud existuje statická metoda`Symbol.hasInstance`,pak ji jen zavolá: `Třída[Symbol.hasInstance](obj)`.Ta by měla vrátit buď`true`, nebo `false`,a jsme hotovi. Tímto způsobem si můžeme chování`instanceof` sami nastavit.
For example:
Například:
```js run
//setupinstanceOfcheck that assumes that
//anything with canEat property is an animal
classAnimal {
//nastavíme ověřeníinstanceOftak, aby předpokládalo,
//že všechno, co má vlastnost můžeŽrát, je zvíře
classZvíře {
static [Symbol.hasInstance](obj) {
if (obj.canEat) return true;
if (obj.můžeŽrát) return true;
}
}
let obj = {canEat: true };
let obj = {můžeŽrát: true };
alert(obj instanceofAnimal); // true:Animal[Symbol.hasInstance](obj) is called
alert(obj instanceofZvíře); // true:zavolá se Zvíře[Symbol.hasInstance](obj)
```
2.Most classes do not have`Symbol.hasInstance`.In that case, the standard logic is used: `obj instanceOfClass` checks whether `Class.prototype`is equal to one of the prototypes in the`obj` prototype chain.
2.Většina tříd nemá`Symbol.hasInstance`.V tom případě je použita standardní logika: `obj instanceOfTřída` zjistí, zda se `Třída.prototype`rovná některému z prototypů v prototypovém řetězci objektu`obj`.
Here's the illustration of what `rabbit instanceofAnimal` compares with `Animal.prototype`:
Na tomto obrázku je vidět, co `králík instanceofZvíře` porovnává se `Zvíře.prototype`:

By the way, there's also a method[objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf),that returns `true` if`objA`is somewhere in the chain of prototypes for`objB`.So the test of`obj instanceofClass` can be rephrased as `Class.prototype.isPrototypeOf(obj)`.
Mimochodem, existuje také metoda[objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf),která vrátí `true`, jestliže se`objA`nachází někde v prototypovém řetězci objektu`objB`.Test`obj instanceofTřída` tedy lze přepsat na `Třída.prototype.isPrototypeOf(obj)`.
It's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
Veselé je, že samotný konstruktor `Třída` se na ověřování nepodílí! Záleží jen na prototypovém řetězci a na `Třída.prototype`.
That can lead to interesting consequences when a`prototype`property is changed after the object is created.
To může vést k zajímavým důsledkům, když je vlastnost`prototype`změněna po vytvoření objektu.
Like here:
Například zde:
```js run
functionRabbit() {}
letrabbit = newRabbit();
functionKrálík() {}
letkrálík = newKrálík();
//changed the prototype
Rabbit.prototype = {};
//změníme prototyp
Králík.prototype = {};
// ...not a rabbit any more!
// ...už to není králík!
*!*
alert(rabbit instanceofRabbit ); // false
alert(králík instanceofKrálík ); // false
*/!*
```
## Bonus: Object.prototype.toStringfor the type
## Bonus: Object.prototype.toStringpro typ
We already know that plain objects are converted to string as `[object Object]`:
Už víme, že plané objekty se převádějí na řetězec jako `[object Object]`:
```js run
let obj = {};
alert(obj); // [object Object]
alert(obj.toString()); //the same
alert(obj.toString()); //totéž
```
That's their implementation of`toString`.But there's a hidden feature that makes`toString`actually much more powerful than that. We can use it as an extended`typeof`and an alternative for `instanceof`.
Taková je jejich implementace metody`toString`.Existuje však skrytá vlastnost, která činí`toString`ve skutečnosti mnohem silnější. Můžeme ji používat jako rozšířený`typeof`a alternativu pro `instanceof`.
Sounds strange? Indeed. Let's demystify.
Zní to zvláštně? Určitě ano. Odhalme to.
By [specification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), the built-in`toString`can be extracted from the object and executed in the context of any other value. And its result depends on that value.
Podle [specifikace](https://tc39.github.io/ecma262/#sec-object.prototype.tostring) může být vestavěný`toString`extrahován z objektu a spuštěn v kontextu jakékoli jiné hodnoty. A na oné hodnotě pak závisí jeho výsledek.
-For a number, it will be `[object Number]`
-For aboolean, it will be `[object Boolean]`
-For `null`: `[object Null]`
-For `undefined`: `[object Undefined]`
-For arrays: `[object Array]`
- ...etc (customizable).
-Pro číslo to bude `[object Number]`
-Proboolean to bude `[object Boolean]`
-Pro `null`: `[object Null]`
-Pro `undefined`: `[object Undefined]`
-Pro pole: `[object Array]`
- ...atd. (nastavitelně).
Let's demonstrate:
Předveďme si to:
```js run
//copy toString method into a variable for convenience
letobjectToString = Object.prototype.toString;
//pro přehlednost si zkopírujeme metodu toString do proměnné
Here we used[call](mdn:js/function/call) as described in the chapter[](info:call-apply-decorators) to execute the function `objectToString` in the context`this=arr`.
Zde jsme použili metodu[call](mdn:js/function/call), popsanou v kapitole[](info:call-apply-decorators), ke spuštění funkce `metodaToString` v kontextu`this=pole`.
Internally, the`toString`algorithm examines`this`and returns the corresponding result. More examples:
Vnitřně algoritmus metody`toString`prozkoumává`this`a vrací odpovídající výsledek. Další příklady:
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.