1

I'm working on a simple debug function that evaluates a closure and gets all the relevant variables names in node.js. It should work at runtime. So, is there a way to automatically capture all the variable names in a closure? For example, is it possible to know the existence of "b", "c" and "d" variables in the following case?

var d=3;
function a(c){ 
   var b = true;
   eval( debug(/* need to access in runtime something like ["b","c","d"] */) );

}
function debug(vars){ 
   var txt = "";
   for(var i=0; i<vars.length; loop++){
      txt+="console.log('"+vars[i]+":' + " vars[i] + ");"
   }
   return txt
}

I could use brute force to scan a.toString() searching for all the "var " and for all the arguments parameters, but is there a native function to find it or a special variable (something like callee.vars) to find the variables names in the closure?

I know "eval" is a big no, but I'm only using that at development environment.

tieblumer
  • 61
  • 7
  • 1
    At runtime? No. You could do static analysis and instrument your code, but that can also only get you so far. – Felix Kling Oct 28 '15 at 17:19
  • Probably duplicates : http://stackoverflow.com/questions/2336508/javascript-get-access-to-local-variable-or-variable-in-closure-by-its-name – Ortomala Lokni Oct 28 '15 at 17:21
  • Have you tried `debugger;`? – Sebastian Simon Oct 28 '15 at 17:29
  • Felix, I'm trying to avoid this kind of analysis, but I'm afraid its the only way :( Xufox, I'm not looking for a way to debug the code with any external tool nor to stop the code in any way, just to console.log the variables on the closure. – tieblumer Oct 28 '15 at 18:05

1 Answers1

0

Yes there is. Just return a function to close over c and set another var to that closure. Like this.

function a(c){ 
   var b = true;
   return function () {
       console.log(c);
    };
}

var d = a(false); // undefined
d(); // false
colecmc
  • 3,133
  • 2
  • 20
  • 33
  • Thank you colecmc, but I don't want to store the c variable value. Instead I need to know it's name. I will edit my question to explain it better. – tieblumer Oct 28 '15 at 17:32