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

Prototypal inheritance#177

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 3 commits intojavascript-tutorial:masterfromotmon76:1.8.1
Jun 4, 2025
Merged
Show file tree
Hide file tree
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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@

1. `true`,taken from `rabbit`.
2. `null`,taken from `animal`.
3. `undefined`,there's no such property any more.
1. `true`,převezme se z `králík`.
2. `null`,převezme se ze `zvíře`.
3. `undefined`,taková vlastnost již neexistuje.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,30 +2,30 @@ importance: 5

---

#Working with prototype
#Práce s prototypem

Here's the code that creates a pair of objects, then modifies them.
Následuje kód, který vytvoří dva objekty a pak je změní.

Which values are shown in the process?
Jaké hodnoty se v tomto procesu zobrazí?

```js
letanimal = {
jumps: null
letzvíře = {
skáče: null
};
letrabbit = {
__proto__:animal,
jumps: true
letkrálík = {
__proto__:zvíře,
skáče: true
};

alert(rabbit.jumps ); // ? (1)
alert(králík.skáče ); // ? (1)

deleterabbit.jumps;
deletekrálík.skáče;

alert(rabbit.jumps ); // ? (2)
alert(králík.skáče ); // ? (2)

deleteanimal.jumps;
deletezvíře.skáče;

alert(rabbit.jumps ); // ? (3)
alert(králík.skáče ); // ? (3)
```

There should be 3 answers.
Odpovědi by měly být tři.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,32 @@

1.Let's add `__proto__`:
1.Přidejme `__proto__`:

```js run
lethead = {
glasses: 1
lethlava = {
brýle: 1
};

lettable = {
pen: 3,
__proto__:head
letstůl = {
pero: 3,
__proto__:hlava
};

letbed = {
sheet: 1,
pillow: 2,
__proto__:table
letpostel = {
peřina: 1,
polštář: 2,
__proto__:stůl
};

letpockets = {
money: 2000,
__proto__:bed
letkapsy = {
peníze: 2000,
__proto__:postel
};

alert(pockets.pen ); // 3
alert(bed.glasses ); // 1
alert(table.money ); // undefined
alert(kapsy.pero ); // 3
alert(postel.brýle ); // 1
alert(stůl.peníze ); // undefined
```

2.In modern engines, performance-wise, there's no difference whether we take a property from an object or its prototype. They remember where the property was found and reuse it in the next request.
2.V moderních motorech s vylepšeným výkonem není rozdíl mezi tím, zda bereme vlastnost z objektu nebo jeho prototypu. Motory si pamatují, kde byla vlastnost nalezena, a při dalším požadavku to využijí.

For instance, for `pockets.glasses` they remember where they found `glasses` (in `head`),and next time will search right there. They are also smart enough to update internal caches if something changes, so that optimization is safe.
Například pro `kapsy.brýle` si pamatují, kde našly `brýle` (v objektu `hlava`),a příště budou hledat rovnou tam. Jsou také dostatečně chytré, aby si při nějaké změně své vnitřní mezipaměti aktualizovaly, takže tato optimalizace je bezpečná.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,30 +2,30 @@ importance: 5

---

#Searching algorithm
#Vyhledávací algoritmus

The task has two parts.
Tato úloha má dvě části.

Given the following objects:
Máme následující objekty:

```js
lethead = {
glasses: 1
lethlava = {
brýle: 1
};

lettable = {
pen: 3
letstůl = {
pero: 3
};

letbed = {
sheet: 1,
pillow: 2
letpostel = {
peřina: 1,
polštář: 2
};

letpockets = {
money: 2000
letkapsy = {
peníze: 2000
};
```

1.Use `__proto__`to assign prototypes in a way that any property lookup will follow the path: `pockets` -> `bed` -> `table` -> `head`.For instance, `pockets.pen` should be`3` (found in `table`), and `bed.glasses` should be`1` (found in `head`).
2.Answer the question: is it faster to get `glasses` as `pockets.glasses` or `head.glasses`?Benchmark if needed.
1.Použijte `__proto__`k přiřazení prototypů takovým způsobem, že každé hledání vlastností bude dodržovat cestu: `kapsy` -> `postel` -> `stůl` -> `hlava`.Například `kapsy.pero` by mělo být`3` (nalezeno ve `stůl`) a `postel.brýle` by mělo být`1` (nalezeno v `hlava`).
2.Odpovězte na otázku: je rychlejší získat `brýle` jako `kapsy.brýle`, nebo jako `hlava.brýle`?Proveďte benchmark, bude-li zapotřebí.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
**The answer: `rabbit`.**
**Odpověď zní: `králík`.**

That's because`this`is an object before the dot, so `rabbit.eat()`modifies `rabbit`.
Je to proto, že`this`je objekt před tečkou, takže `králík.žer()`změní objekt `králík`.

Property lookup and execution are two different things.
Hledání vlastnosti a spouštění metody jsou dvě různé věci.

The method `rabbit.eat` is first found in the prototype, then executed with`this=rabbit`.
Metoda `králík.žer` je nejprve nalezena v prototypu a pak je spuštěna s`this=králík`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,22 +2,22 @@ importance: 5

---

#Where does it write?
#Kam se to zapíše?

We have `rabbit` inheriting from `animal`.
Máme objekt `králík` zděděný z objektu `zvíře`.

If we call `rabbit.eat()`,which object receives the `full` property: `animal` or `rabbit`?
Jestliže zavoláme `králík.žer()`,který objekt získá vlastnost `sytý`: `zvíře` nebo `králík`?

```js
letanimal = {
eat() {
this.full = true;
letzvíře = {
žer() {
this.sytý = true;
}
};

letrabbit = {
__proto__:animal
letkrálík = {
__proto__:zvíře
};

rabbit.eat();
králík.žer();
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,80 @@
Let's look carefully at what's going on in the call `speedy.eat("apple")`.
Podívejme se pozorně na to, co se děje při volání `rychlý.žer("jablko")`.

1.The method `speedy.eat` is found in the prototype(`=hamster`), then executed with`this=speedy` (the object before the dot).
1.Metoda `rychlý.žer` je nalezena v prototypu(`=křeček`) a pak se spustí s`this=rychlý` (objekt před tečkou).

2.Then `this.stomach.push()`needs to find `stomach` property and call`push` on it. It looks for `stomach` in `this` (`=speedy`),but nothing found.
2.Pak `this.žaludek.push()`musí najít vlastnost `žaludek` a zavolat na ní`push`. Hledá `žaludek` v `this` (`=rychlý`),ale nic nenajde.

3.Then it follows the prototype chain and finds `stomach` in `hamster`.
3.Pak následuje řetězec prototypů a najde `žaludek` v objektu `křeček`.

4.Then it calls`push` on it, adding the food into *the stomach of the prototype*.
4.Pak na něm volá`push`, čímž přidá potravu do *žaludku prototypu*.

So all hamsters share a single stomach!
Všichni křečci tedy sdílejí jediný žaludek!

Both for `lazy.stomach.push(...)` and `speedy.stomach.push()`, the property `stomach` is found in the prototype (as it's not in the object itself), then the new data is pushed into it.
Jak pro `líný.žaludek.push(...)`, tak pro `rychlý.žaludek.push()` je vlastnost `žaludek` nalezena v prototypu (protože není v samotném objektu) a pak jsou do ní vložena nová data.

Please note that such thing doesn't happen in case of a simple assignment`this.stomach=`:
Prosíme všimněte si, že při jednoduchém přiřazení`this.žaludek=` se to nestane:

```js run
lethamster = {
stomach: [],
letkřeček = {
žaludek: [],

eat(food) {
žer(potrava) {
*!*
//assign to this.stomach instead ofthis.stomach.push
this.stomach = [food];
//přiřazení do this.žaludek namístothis.žaludek.push
this.žaludek = [potrava];
*/!*
}
};

letspeedy = {
__proto__:hamster
letrychlý = {
__proto__:křeček
};

letlazy = {
__proto__:hamster
letlíný = {
__proto__:křeček
};

//Speedy one found the food
speedy.eat("apple");
alert(speedy.stomach ); //apple
//Rychlý křeček našel potravu
rychlý.žer("jablko");
alert(rychlý.žaludek ); //jablko

//Lazy one's stomach is empty
alert(lazy.stomach ); // <nothing>
//Žaludek líného křečka je prázdný
alert(líný.žaludek ); // <nic>
```

Now all works fine, because `this.stomach=`does not perform a lookup of `stomach`. The value is written directly into`this` object.
Teď vše funguje správně, protože `this.žaludek=`nehledá `žaludek`, ale hodnota se zapíše přímo do objektu`this`.

Also we can totally avoid the problem by making sure that each hamster has their own stomach:
Problému se můžeme zcela vyhnout i tak, že zajistíme, aby každý křeček měl svůj vlastní žaludek:

```js run
lethamster = {
stomach: [],
letkřeček = {
žaludek: [],

eat(food) {
this.stomach.push(food);
žer(potrava) {
this.žaludek.push(potrava);
}
};

letspeedy = {
__proto__:hamster,
letrychlý = {
__proto__:křeček,
*!*
stomach: []
žaludek: []
*/!*
};

letlazy = {
__proto__:hamster,
letlíný = {
__proto__:křeček,
*!*
stomach: []
žaludek: []
*/!*
};

//Speedy one found the food
speedy.eat("apple");
alert(speedy.stomach ); //apple
//Rychlý křeček našel potravu
rychlý.žer("jablko");
alert(rychlý.žaludek ); //jablko

//Lazy one's stomach is empty
alert(lazy.stomach ); // <nothing>
//Žaludek líného křečka je prázdný
alert(líný.žaludek ); // <nic>
```

As a common solution, all properties that describe the state of a particular object, like `stomach` above, should be written into that object. That prevents such problems.
Běžné řešení je, že všechny vlastnosti, které popisují stav určitého objektu, jako třeba uvedený `žaludek`, by měly být zapisovány přímo do tohoto objektu. Tím předejdeme takovýmto problémům.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,34 +2,34 @@ importance: 5

---

#Why are both hamsters full?
#Proč jsou oba křečci sytí?

We have two hamsters: `speedy` and `lazy` inheriting from the general `hamster` object.
Máme dva křečky: `rychlý` a `líný`, kteří jsou zděděni z obecného objektu `křeček`.

When we feed one of them, the other one is also full. Why? How can we fix it?
Když jednoho z nich nakrmíme, bude sytý i ten druhý. Proč? Jak to můžeme opravit?

```js run
lethamster = {
stomach: [],
letkřeček = {
žaludek: [],

eat(food) {
this.stomach.push(food);
žer(potrava) {
this.žaludek.push(potrava);
}
};

letspeedy = {
__proto__:hamster
letrychlý = {
__proto__:křeček
};

letlazy = {
__proto__:hamster
letlíný = {
__proto__:křeček
};

//This one found the food
speedy.eat("apple");
alert(speedy.stomach ); //apple
//Tento křeček nalezl potravu
rychlý.žer("jablko");
alert(rychlý.žaludek ); //jablko

//This one also has it, why? fix please.
alert(lazy.stomach ); //apple
//Tento ji má také, proč? Opravte to, prosíme.
alert(líný.žaludek ); //jablko
```

Loading

[8]ページ先頭

©2009-2025 Movatter.jp