What is a 'Closure'?

前端 未结 23 1556
星月不相逢
星月不相逢 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:53

    A closure is a stateful function that is returned by another function. It acts as a container to remember variables and parameters from its parent scope even if the parent function has finished executing. Consider this simple example.

      function sayHello() {
      const greeting = "Hello World";
    
      return function() { // anonymous function/nameless function
        console.log(greeting)
      }
    }
    
    
    const hello = sayHello(); // hello holds the returned function
    hello(); // -> Hello World
    

    Look! we have a function that returns a function! The returned function gets saved to a variable and invoked the line below.

提交回复
热议问题