In conjunction with closures I often read that something closes over something else as a means to explain closures.
Now I don't have much difficulty understanding closures, but "closing over" appears to be a more fundamental concept. Otherwise one would not refer to it to explain closures, would one?
What is the exact definition of closing over, and what is the something and the something else? Where does the term come from?
close over somebody/something. to surround and cover somebody/something.
The term "closed-over" variable in that post means that the variable is not accessible by the caller of the function; it is neither seen nor modifiable from the context where the function is being called.
Consider:
something closes over something else
|_______| |_________| |____________|
| | |
subject verb object
Here:
Consider a simple function:
function add(x) {
return function closure(y) {
return x + y;
};
}
Here:
add
has only one variable, named x
, which is not a free variable because it is defined within the scope of add
itself.closure
has two variables, named x
and y
, out of which x
is a free variable because it is defined in the scope of add
(not closure
) and y
is not a free variable because it is defined in the scope of closure
itself.Hence, in the second case the function named closure
is said to “close over” the variable named x
.
Therefore:
closure
is said to be a closure of the variable named x
.x
is said to be an upvalue of the function named closure
.That's all there is to it.
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