What is a 'Closure'?

前端 未结 23 1552
星月不相逢
星月不相逢 2020-11-22 08:02

I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?

23条回答
  •  遥遥无期
    2020-11-22 08:54

    In a normal situation, variables are bound by scoping rule: Local variables work only within the defined function. Closure is a way of breaking this rule temporarily for convenience.

    def n_times(a_thing)
      return lambda{|n| a_thing * n}
    end
    

    in the above code, lambda(|n| a_thing * n} is the closure because a_thing is referred by the lambda (an anonymous function creator).

    Now, if you put the resulting anonymous function in a function variable.

    foo = n_times(4)
    

    foo will break the normal scoping rule and start using 4 internally.

    foo.call(3)
    

    returns 12.

提交回复
热议问题