1

我想从我的对象树中生成一些代码。为了生成所需的导入语句,我需要从类实例中找出给定类的源代码位置。

我已经能够获得预期的MyClass名称

var name = instance.constructor.name;

但不是源代码位置

'/src/package/myClass.js'

=> 怎么做?

对于 Java,它会像这里描述的那样工作:

查找从哪里加载 java 类

如果我使用 dir(constructor) 检查 Chrome 开发人员工具中的构造函数,我可以看到一些属性

[[FunctionLocation]]: myClass.js:3

如果我将鼠标悬停在它上面,我可以看到想要的路径。如何以编程方式获取该属性?

在此处输入图像描述

编辑

刚刚发现 [[FunctionLocation]] 不可访问:

以编程方式访问函数位置

4

2 回答 2

1

document.currentScript适用于除 IE 之外的所有浏览器。你可以像这样使用它:

var script = document.currentScript;
var fullUrl = script.src;
于 2019-04-18T14:05:24.717 回答
0

一个可能的解决方法似乎是打电话

determineImportLocation(){
    var stack = new Error().stack;
    var lastLine = stack.split('\n').pop();
    var startIndex = lastLine.indexOf('/src/');
    var endIndex = lastLine.indexOf('.js:') + 3;
    return '.' + lastLine.substring(startIndex, endIndex);
}

在构造函数中MyClass并将其存储以供以后访问:

constructor(name){
    this.name = name;
    if(!this.constructor.importLocation){
        this.constructor.importLocation = this.determineImportLocation();
    }                       
}

但是,这将需要修改我想要的所有类import。如果有不需要修改类本身的解决方案,请告诉我。

在此处输入图像描述

于 2019-04-18T14:26:59.737 回答