
Question:
Are there any ability to get closure variables list (Ok, maybe all scope variables) in JavaScript?
Sample:
function factory(){
var _secret = "Some secret";
return function(code){
// How to get parent function variables names here?
// ...
}
}
var inside = factory();
inside();
Answer1:Assuming this is for debugging purposes, you can try parsing the function body and evaluating identifiers found:
<pre class="snippet-code-js lang-js prettyprint-override">function getvars(fn, _eval) {
var words = String(fn).replace(/".*?"|'.*?'/g, '').match(/\b[_A-Za-z]\w*/g),
ret = {}
words.forEach(function(w) {
try { ret[w] = _eval(w) } catch (e) {};
});
return ret;
}
function factory() {
var _secret = "Some secret";
var _other = "Other secret";
return function(code){
var vars = getvars(factory, _ => eval(_));
return vars;
}
}
vars = factory()();
document.write('<pre>'+JSON.stringify(vars,0,3));
Needless to say, this is an extremely naive way to deal with code, so handle it with care.
Answer2:There's no comprehensive way to get a list of all variables in scope. You could enumerate over the this
object, but that will still only give you a list of the <em>enumerable</em> objects on this
, and even at that there will still be things like function arguments that aren't on this
.
So no, this cannot be done. Also check out this <a href="https://stackoverflow.com/questions/2051678/getting-all-variables-in-scope" rel="nofollow">similar question</a>.
Answer3:No, it isn't possible. ECMAScript specification doesn't expose <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-environment-records" rel="nofollow">Enviroment Record</a> objects to end user anywhere.
Answer4:Since the primary concept of a closure is scope, and vars inside a closure are private, there can be no way to achieve this without exposing them somehow, like via a method.
What are you really trying to achieve?