Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I know what a closure is, but I still dont understand why (or when) you would use them

My understanding of closures is that they are essentially a function which uses a variable that you would assume would be out of scope. I guess heres an example I saw the other day:

function closureMaker(somearg)
{
    var local_value = 7;
    function funcToReturn(arg1, arg2)
    {
        return local_value + somearg + arg1 + arg2;
    }
    return funcToReturn;
}
var myClosure = closureMaker(6);  //make the closure
myClosure(2, 3);                  //using it

Now the closure has local_value and even the original arg, somearg. But I dont get why these are helpful. What is the point of using the 'free' variable local_value or even more unknown to me, why would you use the argument of closureMaking function in your closure function?

I'm more interested in how this is used in javascript, Is this used a lot for AJAX requests and objects?

I got the what. I need the why.

like image 906
fumanchuu Avatar asked Aug 09 '10 16:08

fumanchuu


1 Answers

One of the most practical and widely spread usage of closures is to implement private or privileged members for example, for example:

function Test (param) {
  var secret = 3;
  function privateMethod() {
    //...
  }
  this.publicMember = param;
  this.privilegedMember = function () {
    return secret * param;
  };
}

var foo = new Test(10);
foo.privilegedMember(); // 30
foo.secret; // undefined

The module pattern is also a good example that can use the same principle, e.g.:

var myModule = (function () { 
  var obj = {}, privateVariable = 1; 

  function privateMethod() { 
    // ... 
  } 

  obj.publicProperty = 1; 
  obj.publicMethod = function () { 
    // private members available here... 
  }; 

  return obj; 
}());
like image 173
Christian C. Salvadó Avatar answered Nov 11 '22 15:11

Christian C. Salvadó