0

I have a class:

// 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
  }


}

and here I create a new instance:

// SomeModule.ts

const testFunction = () => {
    return new MyClass();
}

I don't want to have to pass an extra parameter to the constructor to indicate who created it. I want to know inside the constructor the module or the function in which a new instance of the MyClass was created.

but-why
  • 533
  • 3
  • 10
  • 1
    but-why would you want to do that? (JK, couldn't resist). Your question indicates that you most likely have a design issue that you are attempting to smooth over or correct with this idea. I suppose you would have some conditional statements in your constructor based upon which function instantiated the class? – Randy Casburn Feb 13 '21 at 14:58
  • 1
    Seems like an [XY Problem](https://xyproblem.info) – Randy Casburn Feb 13 '21 at 15:00
  • @RandyCasburn It's mostly for logging purposes. – but-why Feb 13 '21 at 15:01

1 Answers1

1

I want to know inside the constructor the module or the function in which a new instance of the MyClass was created.

That's not possible. And you shouldn't need to know anyway. If it actually is important, you should be passing it as an explicit argument.

It's mostly for logging purposes.

For that use case, you might find that a stack trace is enough (see Print current stack trace in JavaScript and related topics). A better practice though is to pass a logger object that contains the relevant context information and uses it to enrich the log calls.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375