简体   繁体   中英

How to find a JavaScript variable's transitive usage through function calls?

Suppose I have access to the full set of source that could potentially be using a JavaScript variable foo .

Some of the source code looks like this:

foo.bar = 'baz';

(function(a, b, c) {
    a();
    b.bar = 'whee';
    c();
}(fn, foo, fn));

Are there any tools available (ESLint rules, NPM modules, etc.) that could identify all usages of the foo variable here? I'm after a list of all access of the variable, including within scopes and including nested objects. So, it would have to identify:

  • The foo.bar usage in the global scope
  • The foo usage in the function invocation
  • The b.bar call is an access of foo.bar

http://ternjs.net/doc/manual.html#infer seems like a good lead:

infer.findRefs(ast: AST, scope: Scope, name: string, refScope: Scope, f: fn(AST, Scope))
Will traverse the given syntax tree, using scope as the starting scope, looking for references to variable name that resolve to scope refScope, and call f with the node of the reference and its local scope for each of them.

infer.findPropRefs(ast: AST, scope: Scope, objType: Obj, propName: string, f: fn(AST))
Analogous to findRefs, but used to look for references to a specific property instead. Whereas findRefs is precise, this is dependent on type inference, and thus can not be relied on to be precise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM