如何通过函数调用找到JavaScript变量的传递用法?

时间:2016-03-03 01:01:37

标签: javascript parsing esprima esprima.js

假设我可以访问可能使用JavaScript变量foo的完整源代码。

部分源代码如下所示:

foo.bar = 'baz';

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

是否有可用的工具(ESLint规则,NPM模块等)可以识别foo变量的所有用法?我正在查看变量的所有访问列表,包括在范围内并包括嵌套对象。所以,它必须确定:

  • 全局范围内的foo.bar用法
  • 函数调用中的foo用法
  • b.bar来电是foo.bar
  • 的访问权限

1 个答案:

答案 0 :(得分:1)

http://ternjs.net/doc/manual.html#infer似乎是一个很好的领导:

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.