What is a 'Closure'?

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

    Currying : It allows you to partially evaluate a function by only passing in a subset of its arguments. Consider this:

    function multiply (x, y) {
      return x * y;
    }
    
    const double = multiply.bind(null, 2);
    
    const eight = double(4);
    
    eight == 8;
    

    Closure: A closure is nothing more than accessing a variable outside of a function's scope. It is important to remember that a function inside a function or a nested function isn't a closure. Closures are always used when need to access the variables outside the function scope.

    function apple(x){
       function google(y,z) {
        console.log(x*y);
       }
       google(7,2);
    }
    
    apple(3);
    
    // the answer here will be 21
    

提交回复
热议问题