File tree Expand file tree Collapse 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 Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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"
You can’t perform that action at this time.
0 commit comments