如何使用Uglify.js解析和迭代原型方法?

How to parse and iterate prototype methods with Uglify.js?

我想使用 uglify js 2 解析一些 JavasScript 代码以列出给定 "class" 的所有方法。在我的例子中,TreeWalker returns 一个节点 name : null 和没有信息可以得出 parent.

的结论

有谁知道不同的方法吗? 我期待 name : "Test.method_name"
到目前为止,我尝试了以下...

parsetests.js

var UglifyJS = require("uglify-js2");
var util = require("util");
var code = require("fs").readFileSync("test.js").toString();
var toplevel = UglifyJS.parse(code);
var log = function(obj, depth) {
    console.log(util.inspect(obj, showHidden=false, depth, colorize=true));
};
var toplevel = UglifyJS.parse(code);
var walker = new UglifyJS.TreeWalker(function(node){
    if (node instanceof UglifyJS.AST_Function ) {
        log(node, 2);        
    }
});
toplevel.walk(walker);

test.js

function Test(argument1) {
    var m = argument1 + "test";
    return this;
}


Test.prototype.method_name = function(first_argument) {
    // body...
    return "a";
};

UglifyJS.TreeWalker节点:

{ end:
   { file: null,
     comments_before: [],
     nlb: true,
     endpos: 156,
     pos: 155,
     col: 0,
     line: 10,
     value: '}',
     type: 'punc' },
  start:
   { file: null,
     comments_before: [],
     nlb: false,
     endpos: 111,
     pos: 103,
     col: 29,
     line: 7,
     value: 'function',
     type: 'keyword' },
  body:
   [ { end: [Object],
       start: [Object],
       value: [Object] } ],
  cname: undefined,
  enclosed: undefined,
  parent_scope: undefined,
  uses_eval: undefined,
  uses_with: undefined,
  functions: undefined,
  variables: undefined,
  directives: undefined,
  uses_arguments: undefined,
  argnames:
   [ { end: [Object],
       start: [Object],
       thedef: undefined,
       name: 'first_argument',
       scope: undefined,
       init: undefined } ],
  name: null }

在你的例子中,函数没有名字,它被分配给一个有名字的 属性。您必须按如下方式命名您的函数:

Test.prototype.method_name = function method_name(first_argument) {
    // body...
    return "a";
};

我编写了一个能够解析和识别这些语法的脚本。我在 https://github.com/s-a/deep-js.

开源了它

目前它涵盖了 https://github.com/s-a/deep-js/blob/3c1e52b75be197ff19a5530d011e999416e21afd/use-case-main.js 中描述的大量用例 并用 https://github.com/s-a/deep-js/tree/3c1e52b75be197ff19a5530d011e999416e21afd/test. You can see the results at https://travis-ci.org/s-a/deep-js/builds/58511486 进行了测试。 当前代码状态有限。例如,如果 this 用于另一个 var,如 self,则当前无法解析。深层嵌套赋值和命名空间是另一个问题。不过到目前为止,如果代码复杂度不是太高,它是稳定的。