Closure Because of What it Can Do or Because it Does

后端 未结 2 1031
迷失自我
迷失自我 2021-02-01 22:23

Ok, this is a bit of a pedantic question but I\'d like to make sure I\'m understanding the definition correctly. Is the closure moniker used to describe anonymous functions that

2条回答
  •  北海茫月
    2021-02-01 22:56

    Assuming you mean within the context of computer science...

    A closure is a first class function which captures the lexical bindings of free variables in its defining environment. Once it has captured the lexical bindings the function becomes a closure because it "closes over" those variables.

    Note this means closures only exist at run time.

    For a function to be a closure is orthogonal to the function being anonymous or named. You can create a language that allows you to define named functions to be closures.

    Here is a "named" closure in Python:

    def maker():
      count=[0]
      def counter():
        count[0]=count[0]+1
        return count[0]
      return counter
    

提交回复
热议问题