I am curious for the line 20 explanation in my example code.
On line 9 variable with name
func1is declared. It's assigned to the closure that is returned by the functionfoo()invocation.`
I know that the invocation of the function foo() returns both the function bar and the pointer to the variable a which is in its lexical scope. Since closure is a function combined with all of the variables in its lexical scope, including function and class names, can I say that I am assigning the variable func1 to the closure?
Is this explanation uses the right words and not vague? Could you suggest a better and more concise explanation and paraphrase line 20?
function foo() {
let a = 1;
return function bar() {
a += 100;
console.log(a);
}
}
let func1 = foo();
let func2 = foo();
func1(); // ???
func2(); // ???
func1(); // ???
func2(); // ???
/*
On line 9 variable with name `func1` is declared.
!! It's assigned to the closure that is returned by the function `foo()` invocation.
The closure contains a pointer to the variable `a` that is in the lexical scope of the function `bar` that is returned by the `foo` invocation.
On line 10 variable with name `func2` is declared. It's assigned to the value of closure that is returned by the function `bar()` invocation. The closure contains a pointer to the variable `a` that is in the lexical scope of the function `bar`.
Variables accessible through the closure during the `func1` invocation and `func2` invocation are two separate independent variables that just happen to have the same name (`a`).
That is, this program would print the following to the console:
- 101
- 101
- 201
- 201
*/
