scope - Searching local javascript variables by name patterns -


in javascript, local variables not live on object i'm aware of. is,

function foo() {     const x = 2;      self.x; // undefined     this.x; // undefined     window.x; // undefined     x; // 2,     eval('x'); // 2 } 

the last option eval('x') shows possible refer these variables name. i'm looking extend , access variable using name pattern:

function foo() {     // code not under direct control     function foobar_abc() {}     function other_functions() {}      // code under control     const matchingfunction = // find function name matching 'foobar_*' } 

if lived on object, use myobject[object.keys(myobject).find((key) => key.startswith('foobar_'))]. if in global scope, myobject window , works.

the fact eval able access variable name implies value available somewhere. there way find variable? or must resort techniques re-write (potentially complex) code not under direct control?

i'm targeting modern browsers, , in use case don't mind using eval or hacky solutions. arbitrary code being executed, because execution of user-provided code purpose.

another option use code parsing deduce function names using javascript ast (abstract syntax tree) library. "esprima" package place look:

https://www.npmjs.com/package/esprima

so can do

import esprima 'esprima'  const usercodestructure = esprima.parsescript( userprovidedjavascriptstring );  const alltoplevelfunctiondeclarations = usercodestructure.body.filter( declaration => declaration.type === "functiondeclaration" );  const alltoplevelfunctionnames = alltoplevelfunctiondeclarations.map( d => d.id ); 

i haven't tried myself documentation suggests should work (or it):

http://esprima.readthedocs.io/en/latest/


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -