Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure Definition and Example

Tags:

closures

what is closure and its correspondence example ?

I have research a lot and could not understand. Please explain in generic programming language concept aspect and specific programming language aspect.

Please help.

Thanks.

like image 451
nicholas Avatar asked Jul 21 '10 04:07

nicholas


People also ask

What is the best definition of closure?

Closure is the end or the closing down of something. It can be physical — like the closure of your local library — or emotional, like the closure you experience when you finally come to terms with the end of a romance. Closure comes from the Latin claus ("shut"), and it has many different shades of meaning.

What is close example?

Example SentencesClose the lid on the box tightly. The door opened and closed so quietly that I didn't notice he had come in the room.

Had a closure meaning?

the feeling or act of bringing an unpleasant situation, time, or experience to an end, so that you are able to start new activities: a sense of closure. to achieve/reach closure.


2 Answers

A closure is basically a function B nested inside a function A that can access A's local variables:

function A() {
    var x = 5;

    function B() {
        print(x);
    }

    return B;
}

If you come from a C++ background, this is rather hard to digest. When we try to call the function returned by A, what x will it refer to? Won't that x be invalid since A() terminated?

The answer is that x actually lives on. That B we returned actually carries x around with it implicitly. Cool, eh?

In a more general sense, a closure is a function bound to some data. In a language without closures like C, every program has a fixed number of functions. With closures, you can, in a sense, "create functions" by binding them to dynamic data. Of course, nobody's stopping you from emulating closures in C, but it can be a pain sometimes.

Closures are really useful. For instance, suppose we want to implement our own "for loop":

function loop(count, f) {
    for (var i = 0; i < count; i++)
        f(i);
}

var array = [0,1,2,3,4];

loop(5, function(i) {
    print(array[i]);
});

Being allowed to access outside variables without doing a bunch of extra nonsense keeps code nice and simple. Without closures, you might have to pass a context variable to the loop function instead:

function loop(count, f, ctx) {
    for (var i = 0; i < count; i++)
        f(i, ctx);
}

var array = [0,1,2,3,4];

loop(5, function(i, ctx) {
    print(ctx[i]);
}, array);

Another example: suppose we want to register a callback in jQuery, but it may be executed long after the function and its caller and its caller's caller are done running:

$(document).ready(function(){

    var clicked = 0;

    $('#button').click(function(){
        clicked++;
        alert("You've pressed the button " + clicked + " times.");
    });

});

If JavaScript were more like C++ (before C++0x), that clicked variable would be long gone by the time the function given to $(document).ready() was called, and the button clicking callback would have undefined behavior.

like image 168
Joey Adams Avatar answered Nov 10 '22 01:11

Joey Adams


Here is how I think of a closure....

A function object consists of two things. The first thing is the code for the function, the second is the scope in which it executes. In a closure, the scope in which the function executes and the code are detached from each other. The same code can execute in a variety of scopes.

If this were allowed in a completely unrestricted way it would result in great confusion. Even when it's something as loose as dynamic scoping (the function inherits the scope of the place where it was called from) it becomes very confusing.

Closures are a convenient way of specifying scope rules that make a lot of sense because they only require reading the code instead of tracing it. In a closure, the function gets the scope of where it was declared. If it was declared while executing another function, it gets the scope of that specific instance of the function's stack. This is a lot simpler and easier to understand than being able to give the closure and arbitrary scope, or dynamic scoping.

Here is an example of a trivial closure in Python:

def outer():
    def closure():
        pass
    return closure

Here the function closure is a closure. It doesn't actually use any variables from the scope in which it was defined, so it's pretty trivial, but it still is one.

Here is a not-so-trivial, but still simple closure in Python:

 def outer(x):
      def closure():
          return x
      return closure
 f1 = outer(5)
 f2 = outer(6)

Calling f1() will return 5 and calling f2() will return 6. As you can see, the function closure is part code, and part scope.

When outer(5) is called, it creates a stack entry for the call that contains a version of the variable x holding the value 5. It then declares the function closure which gets that scope.

When outer(6) is called, it creates a stack entry for the call that contains a version of the variable x holding the value 6. It then declares the function closure which gets that scope.

like image 24
Omnifarious Avatar answered Nov 10 '22 00:11

Omnifarious