What is a 'Closure'?

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

    I'll give an example (in JavaScript):

    function makeCounter () {
      var count = 0;
      return function () {
        count += 1;
        return count;
      }
    }
    
    var x = makeCounter();
    
    x(); returns 1
    
    x(); returns 2
    
    ...etc...
    

    What this function, makeCounter, does is it returns a function, which we've called x, that will count up by one each time its called. Since we're not providing any parameters to x it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.

    Here is my currying example again:

    function add (a) {
      return function (b) {
        return a + b;
      }
    }
    
    var add3 = add(3);
    
    add3(4); returns 7
    

    What you can see is that when you call add with the parameter a (which is 3), that value is contained in the closure of the returned function that we're defining to be add3. That way, when we call add3 it knows where to find the a value to perform the addition.

提交回复
热议问题