Monday, November 7, 2016

closures in JavaScript

What I suggest here is probably really wrong. Instead if you just Google against this topic you'll find stuff like this giving a different explanation. Alright, consider this:

var myClosure = function() {
   counter++;
   alert(counter);
};
myClosure();
myClosure();
myClosure();

 
 

It's gonna fail, right? You can't do plus plus on something undefined, right? Well, what if counter did correspond to a number in a backing store, someplace where state could be kept? It can. You can have this:

var myClosure = (function() {
   var counter = 0;
   return function() {
      counter++;
      alert(counter);
   }
})();
myClosure();
myClosure();
myClosure();

 
 

This code will not break and will moreover throw up three alerts, one after the other, with 1, 2, and 3, in them. We have made counter a privately-scoped variable really only approachable by myClosure and we are using it as a backing store for state. After initial assignment, myClosure behaves in the code immediately above just as it does in the code at the very top of this blog posting. The only difference is that now counter means something.

No comments:

Post a Comment