How do JavaScript closures work?
P粉494151941
2023-08-22 10:16:45
<p>How to explain closures to someone who understands the concept of JavaScript closures (such as functions, variables, etc.), but does not understand closures themselves? </p>
<p>I've looked at the Scheme examples given on Wikipedia, but unfortunately they didn't help. </p>
In JavaScript, each function maintains a link to its external lexical environment. The lexical environment is a map of all names (such as variables, parameters) and their values in a scope.
So, whenever you see the
function
keyword, code inside that function can access variables declared outside the function.This will output
Function16
because the functionbar
closes the parameterx
and the variabletmp
, which both exist in the outer function# in the lexical environment of ##foo.
bar
Functions are not required to, together with its link to the lexical environment of function
foo, forms a closure.
return to create a closure. By declaration alone, each function encloses its enclosing lexical environment, forming a closure.
bar
However, sincecan still reference the parameter
xand variable
tmp, even though they are no longer directly in scope.
tmp
The simplest example of a closure is:still exists within
bar's closure, it can be incremented. It will be incremented each time
baris called.
ec
Every function creates a closure because every function has a link to its external lexical environment.is created. In addition to the function parameters and the target object, this execution context also receives a link to the lexical environment of the calling execution context, which means variables declared in the external lexical environment (in the example above, that is,
aand
b) can be accessed from
ec.
A closure is a pair of:
The lexical environment is part of every execution context (stack frame) and is the mapping between identifiers (i.e. local variable names) and values.
Every function in JavaScript maintains a reference to its external lexical environment. This reference is used to configure the execution context created when the function is called. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.
If a function is called by another function, a series of references to the external lexical environment will be created. This chain is called the scope chain.
In the following code,
inner
forms a closure with the lexical environment of the execution context created whenfoo
is called, and the closure contains the variablesecret
: