I apologize in advance for yet another closure question, but I'd like to clarify my understanding of the way closures are implemented in JavaScript.
Consider the following code:
01 'use strict';
02 function foo() {}
03 foo();
I have established in a question earlier in the year that a closure is conceptually (if not actually due to engine optimizations) created here.
And until foo is invoked on line 3 a corresponding execution context is not created.
So as far as I can tell from the spec, when evaluating this code:
FunctionCreate is called, passing in a reference (named "scope") to the "LexicalEnvironment" component of the current execution context. (14.1.19)FunctionCreate calls FunctionInitialize passing "scope" (9.2.5)FunctionInitialize ensures that the [[Environment]] internal slot of the function-object being created is set to the value of "scope" (the reference to the "LexicalEnvironment" component of the current execution context) (9.2.4)Finally, when foo is actually invoked, I find the spec harder to interpret.
PrepareForOrdinaryCall, the "LexicalEnvironment" of the new execution context for the call is set to be the result of calling NewFunctionEnvironment (9.2.1.1)NewFunctionEnvironment copies the reference to the "LexicalEnvironment" component of the outer execution context (the [[Environment]] slot of the function-object) into the Environment record (EnvironmentRecord?) of the "LexicalEnvironment" component of the execution context under construction as the "outer lexical environment reference" (8.1.2.4)Thus closures are implemented in a two step fashion:
EnvironmentRecord(?) sub-component of the "LexicalEnvironment" component of the new execution context.Does this sound about right?
Does this sound about right?
Pretty much. I just wouldn't use the work "copied", rather "linked". To simplify it a little:
Or in pictures:
+----------------+ +----------------+
Function | | [[Environment]] | Outer |
creation | Function |-------------------->| Environment |
| | | |
+----------------+ +----------------+
^
|
|
+----------------+ |
Function | Function | outer environment reference |
execution | Environment |------------------------------+
| |
+----------------+
This happens to every function and depending on your definition of closure1, this makes every function a closure (or not).
1: I believe there are these two takes on what it means for a function to be a closure:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With