获取类构造函数参数名称 [英] Get class constructor argument names
问题描述
我正在为ES类实现某种依赖注入解决方案,为此,我需要知道类构造函数参数的确切名称.
I'm implementing a certain dependency injection solution for ES classes, and for it I need to know exact names of class constructor parameters.
当我得到类或类静态方法的字符串形式时,它确实给出了完整的代码(通常对于函数而言),但是对于类构造函数却没有.
When I get string form of class or class static method, it does give full code (as usually for functions), but for class constructor it does not.
class C { constructor(a, b) { }; static m(x,y) { } }
console.log(C);
console.log(C.constructor);
console.log(C.m);
产生
class C { constructor(a, b) { }; static m(x,y) { } }
ƒ Function() { [native code] }
ƒ m(x,y) { }
结果,我必须解析整个类代码以使用正则表达式提取构造器参数部分
As result, I have to parse whole class code to extract constructor arguments part, using regex like this
C.toString().split(/constructor\s*[^\(]*\(\s*([^\)]*)\)/m)
是否有更干净的方法来获取构造函数参数名称?
Is there any cleaner way to get constructor argument names?
更新: 感谢您的所有意见和评论,但是我非常清楚缩小的工作原理,TS装饰器的工作方式以及Angular/AngularJS DI的实现方式以及工作方式.它与问题无关.问题是:
Update: Thank you for all your opinions and comments but I'm crystal aware how minification works, how TS decorators work and how Angular/AngularJS DI is implemented and how it works. It is not related to the question. The question is:
是否可以获取构造函数代码,因为函数可以使用?
推荐答案
不应该将参数的名称视为标识要注入到constructor
中的内容的可靠方法.如您所见,JavaScript并非旨在让您以适当的方式检索这些名称,并且如果您在浏览器环境中,则可能在释放代码之前将代码缩小了,从而导致名称丢失.
A parameter's name should not be considered as a reliable way to identify what to inject into a constructor
. As you noticed, JavaScript is not designed to let you retrieve these names in a proper way, and if you're in a browser context, you're probably minifying the code before releasing it, causing the loss of the names.
JavaScript中的依赖注入机制通常依赖于元数据,例如Angular的元数据.它使用TypeScript装饰器将排序后的参数 types 存储在Map
中,该键的键是类本身,而值是类的Array
.然后,可以通过简单的引用比较(或instanceof
)来检查可注入对象池中是否已实例化了所需的类.
Dependency injection mechanisms in JavaScript usually rely on metadata, such as Angular's one. It uses TypeScript decorators to store the ordered parameters types in a Map
whose the key is the class itself, and the value is an Array
of classes. Then, it's possible to check if a required class has already been instantiated in your pool of injectable objects thanks to a simple reference comparison (or instanceof
).
FYI回送是另一个使用TypeScript和依赖项注入的后端框架(在Node.js中运行).
FYI Loopback is another backend framework (running in Node.js) that uses TypeScript and dependency injection.
这篇关于获取类构造函数参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!