89770

Get list of closure variables in Javascript

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?

Recommend

  • How to achieve a private branch in git that “floats” when merging with upstream?
  • Use shared WKWebViewCookies for a request
  • karma-browserify throws error when trying to load modules shimmed with browserify-shim
  • Random characters in CSS class names
  • c#.NET USB device persistent identifier
  • Constant embedded for loop condition optimization in C++ with gcc
  • How to emulate integrated numeric keypad cursor keys in linux
  • What do getresuid() and setresuid() do?
  • jQuery file download plugin
  • Deserialize Dictionary
  • Collapsible Sankey Diagram - D3
  • WooCommerce hook after order is updated?
  • Number of threads being used during Parallel.ForEach
  • help('modules') crashing? Not sure how to fix
  • Updating and removing unique join relationships in CakePHP
  • MySQL: Difference between `… ADD INDEX(a); … ADD INDEX(b);` and `… ADD INDEX(a,b);`?
  • Is there a way to disable a specific event in kendo ui scheduler?
  • Can XOR be expressed using SKI combinators?
  • if some function is not optimized does it mean that all functions where it is declared are not optim
  • Serve file to user over http via php
  • Efficient algorithm to find additions and removals from 2 collections
  • Why doesn't a local variable live long enough for thread::scoped?
  • Enumerating Controls on a Form
  • Scanner nextInt() and hasNextInt() problems
  • Extract All Possible Paths from Expression-Tree and evaluate them to hold TRUE
  • XSLT foreach repeating nodes to flat
  • ThreadStatic in asynchronous ASP.NET Web API
  • Regex to match a string not followed by anything
  • Why use database factory in asp.net mvc?
  • List images(01.png) and descriptions(01.txt) from directory
  • Parse a date string in a specific locale (not timezone!)
  • Alternative To body {overflow:scroll;} That Will Prevent Page Jostling/Wriggling?
  • Play WS (2.2.1): post/put large request
  • D3 nodes and links from JSON with nested arrays of children
  • Master page gives error
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • PHP: When would you need the self:: keyword?
  • WPF Applying a trigger on binding failure
  • Does armcc optimizes non-volatile variables with -O0?
  • How to Embed XSL into XML