What is a 'Closure'?

前端 未结 23 1743
星月不相逢
星月不相逢 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 09:08

    Here is another real life example, and using a scripting language popular in games - Lua. I needed to slightly change the way a library function worked to avoid a problem with stdin not being available.

    local old_dofile = dofile
    
    function dofile( filename )
      if filename == nil then
        error( 'Can not use default of stdin.' )
      end
    
      old_dofile( filename )
    end
    

    The value of old_dofile disappears when this block of code finishes it's scope (because it's local), however the value has been enclosed in a closure, so the new redefined dofile function CAN access it, or rather a copy stored along with the function as an 'upvalue'.

提交回复
热议问题