I have a javascript function, I want to pass the function to another function and then:
For instance:
function foo() {
var a; // ignored
global = 2; // want 'global'
bar(global); // want 'bar'
};
var obj = identifier(foo); // Need to write this function 'identifier'! :)
console.log(obj); // Produces: {globar:2, bar = bar()};
Note: I am looking for a clean way. I have considered turning the function to a string, parsing each line and processing it. I feel this might not be a fool proof plan and there will be a better way. If there is not a better way I'll come back and share my solution.
Thank you
You can use Esprima or another JS AST parser to turn the function into a clean structure. Then you can recursively analyse it. It is a bit too big to write as a StackOverflow answer, but in a nutshell, start with:
var ast = esprima.parse(foo);
Dive into .body, and recursively analyse it. Look for .type == "VariableDeclaration", that will contain local variables. Also take a look at .params of your function, those are also local. As you scan, look for .type == "Indentifier" and .type == "CallExpression"; those will use variables and functions, so check them against your list of local variables. You will need to do it in two passes, first to gather locals, then to find globals. Also, as you find .type == "FunctionDeclaration" or .type == "FunctionExpression", you have to make a new scope: move the local variables list into something like inherited locals, and make a new locals list, in order for the inner scope variables not to bleed into the outer scope.
Lots of details need to be ironed out; you can check ESTree project to see what node types are possible.
Lastly, I'd tentatively agree with zerkms: unless you are writing an editor or something similar, this is likely an XY-problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With