Martin Drautzburg
Martin Drautzburg

Reputation: 5253

What exactly does "closing over" mean?

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?

Upvotes: 30

Views: 4503

Answers (1)

Aadit M Shah
Aadit M Shah

Reputation: 74234

Consider:

something closes over something else
|_______| |_________| |____________|
    |          |             |
 subject      verb        object

Here:

  1. The subject is the closure. A closure is a function.
  2. The closure “closes over” (as in encloses) the set of its free variables.
  3. The object is the set of the free variables of the closure.

Consider a simple function:

function add(x) {
    return function closure(y) {
        return x + y;
    };
}

Here:

  1. The function named add has only one variable, named x, which is not a free variable because it is defined within the scope of add itself.
  2. The function named 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:

  1. The function named closure is said to be a closure of the variable named x.
  2. The variable named x is said to be an upvalue of the function named closure.

That's all there is to it.

Upvotes: 38

Related Questions