Sunday 13 May 2012

Acces to Closure Variables 3

Someone asked me the other day about getting access to a variable captured by a JavaScript closure. I answered him based on this previous post. Then, it occurred to me a different way to get something similar, by modifying the way we define our closure. Instead of capturing the variables, we'll be trapping the function itself, and adding those variables to the function. Well, I better show the code:

//function with a counter keeping track of its invocations
var countableFunction = (function(){
 var me = function (){
  me.counter++;
  //do whatever...
  console.log("called, " + me.counter);

 };
 me.counter = 0;
 return me;
})();


countableFunction();

countableFunction();

console.log("countableFunction has been invoked: " + countableFunction.counter + " times");

So in the end, we have a closure (a function with state) that exposes its state to the outer world, only that the way we add that state creating the closure is slightly different.

No comments:

Post a Comment