2

I have a function which determines the calling function via Function.caller. Is it possible to determine whether the caller belongs to a class, is a class, etc?

(I Know that when function.caller == null it is the root level from which it was called.)

Some code which may help in understand what i'm trying to achieve.

log(component: object, level: LogLevel, category: ILogCategory, message: string)
  {
    if(!component)
      let callingComponent = log.caller;
      // PSEUDOCODE
      if(parent of caller is class)
      callingComponent = class;

      //... 
    }
  }

EDIT

I want to get the class to which the caller of my method belongs to.

Velulian
  • 313
  • 5
  • 15

1 Answers1

1

I see your question as having two parts:

The first roadblock you'll hit is trying to determine who called the function. I know you said you're using Function.caller, but that feature is deprecated. Building code ontop of a deprecated feature doesn't seem like a good idea, even if the features is currently supported across most browsers. So you might take a step back and ask why you care who called the function. The logging use case is a good one (i.e. you want to log what class added the log entry), but I can't think of many other good ones. For the logging use case, you probably just need to add a parameter to the function that allows the caller to pass their name in. If you're dead set on not doing that, you could try using the error throwing technique described here but I can't vouch for it: https://stackoverflow.com/a/29572569/11300565

The second (and main) part of your question (if you can get the caller, how can you tell if its a class?) doesn't have a good answer. One approach would be to make all your classes inherit from some base class and then provide a static typeguard on that base class (MyBaseClass.isInstanceOfMe(unknownObject)) that you could use. Other than implementing something on your own, I'm not aware of a built-in way to detect typescript classes, since they get compiled down to javascript at the end of the day and are difficult to distinguish from objects and functions.

RocketMan
  • 441
  • 4
  • 15