Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> Closure i kolejność wyszukiwania wartości zmiennej
q3d
post 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
  1. function createCounter() {
  2. let counter = 0
  3. const myFunction = function() {
  4. counter = counter + 1
  5. return counter
  6. }
  7. return myFunction
  8. }
  9. const increment = createCounter()
  10. const c1 = increment()
  11. const c2 = increment()
  12. const c3 = increment()
  13. console.log('example increment', c1, c2, c3)


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.
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 26.04.2024 - 12:18