1

Say I have this function:

function test(){
    return a + b + 1;
}

How can I dynamically figure out that it will require globals a and b to be able to run? E.g. something like get_dependencies(test) returns ['a', 'b']

2
  • 1
    FWIW, a and b don't have to be globals, they just have to be defined in the containing scope (which may not be the global scope). Commented Mar 19, 2012 at 9:15
  • I don't think this is possible Commented Mar 19, 2012 at 9:16

2 Answers 2

1

There's no built-in way to do that in standard JavaScript, if you're trying to do it with JavaScript itself.

On nearly all (but not all) JavaScript engines, you can get a form of the source of a function from the function object's toString function, e.g.:

var testSource = test.toString();

...and then of course you could parse that. This is non-standard behavior (the result of calling toString on a function is not defined in the specification), but it's widely-supported. You'd still have to do the parsing to find the symbols.

For the parsing, you have a couple of options. You could try to separate the parser portion of JSLint out of the rest of it, or alternately the terribly-named UglifyJS compressor has a full JavaScript parser which is already separate from the compressor part (see parse-js.js; apparently there's a tiny bit of NodeJS-specific stuff you might want to remove).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @T.J. I might give this a try - I'm guessing there's a regex that's not too complicated that would cover 90% of cases which is good enough for me for now.
@Trindaz: Re the regex: Probably not. Consider the complexity of comments (both styles of them), string literals (both styles of them), regular expression literals, etc. A simple regex giving you, for instance, all of the identifier-like things would be blown up by those. Still, with some pre-processing you could probably do a 90% solution...
@Trindaz: Added some notes to the answer on parsing.
0

You can use a Javascript 'lint' tool that will test your code for common mistakes or oddities.

Some can be found online:

In your case, you might want to isolate individual functions via a regular expression for example, and submit them to such a tool.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.