1

I'm trying to get the name of the function that called another function.

class ABC {
  static method_A() {
    ABC.method_B();
  }

  static method_B() {
    console.log('B method');
    //Need to get the name of the method that called this method (e.g. method_A())
  }
}

I've looked around and there is a deprecated way of doing it and a non-standard way of doing it. But both are not working for me, I'm getting an undefined error when I try to use any of them. Just wanted to make sure is it because they are static methods?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Raza
  • 1,192
  • 4
  • 12
  • 23
  • If you're debugging, breakpoints and stacktraces are the better solution. If you just want to know the order of what happened using the console, why not just A log for itself? – Joseph Sep 04 '15 at 18:40
  • @JosephtheDreamer sadly no, I'm creating a logger for my app. And the logger function needs to know from where it was called in order to send to the server the appropriate error message. – Raza Sep 04 '15 at 18:43
  • 3
    Usually JS loggers initialize themselves with a string to do things like this. [`debug`](https://www.npmjs.com/package/debug) for example. What you want is technically possible since you can use `new Error().stack` to try to figure out a name, but it's gross and probably slow. – loganfsmyth Sep 04 '15 at 18:49
  • 1
    Then you're trying to solve the wrong problem. Instead, of solving the "how to get the function name", try solving "how to get the trace". Errors normally have a `stack` property, containing the stack trace up to when the error happened. – Joseph Sep 04 '15 at 18:52
  • Relevant Question: [How do you find out the caller function in JavaScript?](http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript). Note the accepted answer does not work in your case as you are using strict-mode. So check the second answer. – Spencer Wieczorek Sep 04 '15 at 18:59
  • @loganfsmyth Yeah, that's why I'm trying to look for a better solution. @JosephtheDreamer You are right if I was logging for just the javascript errors. I need to log information in certain cases and send it to the server, so most of the times there won't be an ```Error``` object to start with. @SpencerWieczorek Can you please elaborate on that, I don't see how the second solution will help me. – Raza Sep 04 '15 at 19:44

0 Answers0