Hi I'm reading the book series "You Don't Know JS". I'm on my second pass where I try to get a deeper understanding of the content. While going over the chapter on scopes and closures. The following scenario occurred to me:
Consider this example
function test1(){
var a = 2;
return function(){console.log(a)};
}
var b = test1();
b(); // 2
var c = test1();
c(); // 2
The returned function from "test()" maintains a closure over the scope of "test". So each time we call this returned function we get the value of the variable "a" which in this case is "2". Now consider this example:
function test2() {
var a = Date.now();
return function() {console.log(a)}
}
var b = test2();
b(); // 1551867093995
var c = test2();
c(); // 1551867109249
Each time we execute "test()" the variable "a" gets assigned the time the function "test()" was invoked and returns a function that maintains a closure over the scope of "test()".
We call "test()" on two separate instances assigning the returned function to the variables "b" and "c".
Notice when we call "b()" and "c()" we get 2 different values even though each invocation references the same variable in the same scope (var a).
It seems that each time we invoke a function (for example "test2()") the engine creates a unique instance of the declared functions scope for each invocation of that function, and whatever closure exists, closes on a unique instance of the function scope. It's as if the each function declaration creates a "Scope class" that describes its own scope and each time the function is invoked an instance of that "scope class" is created. Is this really the case? Could someone explain this behavior or point me to resource that give a deeper explanation of JavaScript scopes?
Thank you