Closures

Introduction

A closure is a function that refers to free variables (variables that are used by the function but are defined in an enclosing function). In other words, in JS++, a closure is created when a function is declared inside another function, and the inner function refers to variables declared in the outer function.

The following is a basic example of a closure:

1
2
3
4
5
6
7
8
9
10
11
void foo() {
    int x = 1, y = 2;
     
    // First condition: a function declared inside another function
    void bar() {
        // Second condition: the inner refers to variables of the outer function
        // In this case, we are referring to the outer function's 'x' and 'y'
        // variables.
        int z = x + y;
    }
}

However, another interesting feature of closures is that they can still refer to variables of their containing function after the containing function has returned. Thus, if a containing function returns a function, the returned function can still refer to the variables of its outer function (which returned the returned function). We can illustrate this by modifying the first example and adding a return statement to the inner function:

1
2
3
4
5
6
7
8
9
10
11
void() foo() {
    int x = 1, y = 2;
     
    // First condition: a function declared inside another function
    return void bar() {
        // Second condition: the inner refers to variables of the outer function
        // In this case, we are referring to the outer function's 'x' and 'y'
        // variables.
        int z = x + y;
    };
}

For closures that are still accessing variables from a function that has already returned, the variable values are set to the last value of the variable before the function returned. The variables of the containing function can still be further modified, and references can be modified anywhere (even outside the closure).

Memory Leaks

Closures can create memory leaks.

Closures "hold on" to variables and references even after its containing function has returned. The references must be manually cleared when they are no longer needed.

See Also

External Links

Share

HTML | BBCode | Direct Link