Answer the question
In order to leave comments, you need to log in
Lexical environment and closure. Do I understand correctly?
Hello! I'm new and trying to understand the topic: "Closures in JS".
Please help to understand, tk. I sit and I can not fully understand the following:
Question 1. Do I understand these terms correctly:
The execution context is the environment in which the code is executed. Those. as I understand it, the execution context is a piece of code that is currently being executed.
Before running the JS code, an execution context is created, which in turn is divided into several stages:
1. Binding this
2. Forming the Lexical Environment (lexical environment)
3. Forming the Variable Environment(environments of variables) - it's not clear why? Should
variable data be stored in a lexical environment?
A lexical environment is a kind of hidden object that has 2 components:
a) an environment record is just a repository of data, variables, functions and their values. Those. the values are simply stored in memory for later use.
b) reference to the external environment . I don't understand what this is for. Those. here, as it were, what external data is available in the current environment, right?)
Among other things, I know that when a function is called, a new lexical environment for this function is created each time, and here the question is already directly related to the counter:
function makeCounter() {
let count = 0;
return function() {
return count++;
};
}
let counter1 = makeCounter();
let counter2 = makeCounter();
alert( counter1() ); // 0
alert( counter1() ); // 1
alert( counter2() ); // 0 (независимо)
Answer the question
In order to leave comments, you need to log in
1. In general, the understanding is correct, but not completely.
2. return count++
will return 0, and then increment the counter. If it were return ++counter;
, then the already changed value would be returned. Read the difference between prefix and postfix increments .
3. makeCounter() is called twice, followed by calls to counter1 or counter2 whose LE was created when makeCounter was called.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question