问题描述
我有一堂课:
// MyClass.ts
export class MyClass {
constructor(){
// can I get the name of the module or function which called the constructor here ??
// ex: SomeModule or testFunction
}
}
// SomeModule.ts
const testFunction = () => {
return new MyClass();
}
我不想将额外的参数传递给构造函数来表明它是谁创建的。我想知道在构造函数内部创建 MyClass 的新实例的模块或函数。
解决方法
我想知道在构造函数内部创建 MyClass 的新实例的模块或函数。
这不可能。反正你也不需要知道。如果它确实很重要,您应该将其作为显式参数传递。
主要用于记录目的。
对于该用例,您可能会发现堆栈跟踪就足够了(请参阅 Print current stack trace in JavaScript 和相关主题)。不过,更好的做法是传递一个包含相关上下文信息的记录器对象,并使用它来丰富日志调用。