Exactly what is the difference between a “closure” and a “block”?

前端 未结 6 1103
星月不相逢
星月不相逢 2020-12-12 13:38

I\'ve found that lots of people use the words closure and block interchangeably. Most of these people can\'t explain what they\'re talking about.

S

6条回答
  •  盖世英雄少女心
    2020-12-12 14:00

    A block is something syntactical - A logical unit of statements (more related to scope than to closure).

    if (Condition) {
        // Block here 
    } 
    else {
        // Another block
    }
    

    A closure is related to anoymous functions or classes - An anonymous (function) object, a piece of code that is bound to an environment (with its variables).

    def foo() {
       var x = 0
       return () => { x += 1; return x }
    }
    

    Here foo returns a closure! The local variable x persists through the closure even after foo terminated and can be incremented through calls of the returned anonymous function.

    val counter = foo()
    print counter() // Returns 2
    print counter() // Return 3
    

    Note that's just Ruby in which block and closure are treated similarly since what Ruby calls block is a closure:

    (1..10).each do |x|
        p x
    end
    

    There each-method is passed a closure function (taking a parameter x) which is called a block in Ruby.

提交回复
热议问题