Closure i kolejność wyszukiwania wartości zmiennej |
Closure i kolejność wyszukiwania wartości zmiennej |
15.10.2020, 08:30:38
Post
#1
|
|
Grupa: Zarejestrowani Postów: 98 Pomógł: 7 Dołączył: 10.01.2006 Ostrzeżenie: (0%) |
Klasyczny przykład zaczerpnięty z: https://medium.com/dailyjs/i-never-understo...es-9663703368e8
W opisie jednak znajduje się zdanie: Cytat Line 4. counter = counter + 1. We need to look for the variable counter. Before we look in the local or global execution context, let’s look in our backpack. Let’s check the closure. Lo and behold, the closure contains a variable named counter, its value is 0. After the expression on line 4, its value is set to 1. And it is stored in the backpack again. The closure now contains the variable counter with a value of 1. Dokładnie chodzi mi o fragment: Cytat Before we look in the local or global execution context, let’s look in our backpack. to beletrystyka czy faktycznie kolejność wyszukiwania jest następująca: closure, local, global. 1) Jeżeli tak to dlaczego kod poniżej zwraca błąd "ReferenceError: counter is not defined": Kod function createCounter() { let counter = 1; const myFunction = function () { console.log(counter); let counter = 123; counter++; return counter; }; return myFunction; } czy Kod console.log(counter) nie powinien wziąć wartości zmiennej counter z clouser tej funkcji?2) Druga sprawa: Kod function createCounter() { let counter = 1; const myFunction = function () { let counter = 123; counter++; return counter; }; return myFunction; } Wynikiem tej funkcji jest 124. Wygląda to więc tak, że to zakres lokalny przysłania clouser tej funkcji. |
|
|
Wersja Lo-Fi | Aktualny czas: 26.04.2024 - 12:18 |