Closures are important because they control what is and isn’t in scope in a particular function, along with which variables are shared between sibling functions in the same containing scope.

Definition of the Closure given by Douglas Crockford: crockford.com/javascript/private.html

Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.

Example:

function OuterFunction() {
    var outerVariable = 100;
    function InnerFunction() {
        alert(outerVariable);
    }
    return InnerFunction;
}
var innerFunc = OuterFunction();
innerFunc(); // 100

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.

Example:

var counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();

alert(counter.value()); // 0
counter.increment();
counter.increment();
alert(counter.value()); // 2
counter.decrement();
alert(counter.value()); // 1

0 commenti

Lascia un commento

Segnaposto per l'avatar