Skip to content

Commit 4abbc9e

Browse files
committed
[LES-15.1/st-compl] intro-to-scope-chain-this
Practice/understanding "scope". Working with "bind()" meth, "closure". Worth noting: - all this lesson/practice. FS-dev: B-3 / JS basic
1 parent 812fad4 commit 4abbc9e

File tree

1 file changed

+35
-0
lines changed
  • full-stack-dev/3-js-basic/15-scope-chain-this/15-1-intro-to-scope-chain-this

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Задание 1:
2+
// Как можно подкорректировать код, чтобы внутри setTimeout контекст не терялся и мы то же увидели в консоли 'Маг кастует заклинание!'?
3+
4+
const player = {
5+
name: 'Маг',
6+
castSpell: function () {
7+
console.log(`${this.name} кастует заклинание!`);
8+
},
9+
};
10+
11+
player.castSpell(); // "Маг кастует заклинание!"
12+
13+
setTimeout(player.castSpell.bind(player), 100); // "Маг кастует заклинание!"
14+
15+
// Задание 2:
16+
// Внимательно изучи код. Твоя задача — предсказать, что будет выведено в консоль?
17+
18+
function createCounter(name) {
19+
let count = 0; // Эта переменная живёт в scope функции createCounter
20+
21+
return {
22+
name: name,
23+
log: function () {
24+
count++;
25+
console.log(`${this.name} насчитал: ${count}`);
26+
},
27+
};
28+
}
29+
30+
const counterA = createCounter('Счётчик А');
31+
const counterB = createCounter('Счётчик Б');
32+
33+
counterA.log(); // "Счётчик А насчитал: 1"
34+
counterB.log(); // "Счётчик Б насчитал: 1"
35+
counterA.log(); // "Счётчик А насчитал: 2"

0 commit comments

Comments
 (0)