Definition of closure and example

What is a closure and an example of its correspondence?

I have a lot of research and I could not understand. Please explain in general aspects of the concept of a programming language and a specific aspect of a programming language.

Please, help.

Thank.

+5
source share
3 answers

This is how I think about closing ...

A functional object consists of two things. The first is the code for the function, the second is the area in which it is executed. In closing, the area in which the function is executed and the code are separated from each other. The same code can be executed in different areas.

, . - , ( , ), .

- , , , . , . , . , .

Python:

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

closure . , , , .

-, Python:

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

f1() 5, f2() 6. , closure - .

outer(5), , x, 5. closure, .

outer(6), , x, 6. closure, .

+1

B, A, :

function A() {
    var x = 5;

    function B() {
        print(x);
    }

    return B;
}

++, . , A, x ? x , A() ?

, x . , B , x . , ??

, . , C, . " ", . , C, .

. , , for:

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]);
});

, , . loop:

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);

: , jQuery, , :

$(document).ready(function(){

    var clicked = 0;

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

});

JavaScript ++ ( ++ 0x), clicked , , $(document).ready(), , , undefined.

+9

,

Python: 6 -

& , --- > http://diveintopython3.org/

, . , .

, , .

0
source

All Articles