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.

3
  • 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? Commented Feb 13, 2021 at 14:58
  • 1
    Seems like an XY Problem Commented Feb 13, 2021 at 15:00
  • @RandyCasburn It's mostly for logging purposes. Commented Feb 13, 2021 at 15:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.