0

So say, I have function Hello_world() :

function Hello_world() {
  b();
}

I want to create function b() where b() returns the name of the function in which called it. In this case I want b() returns "Hello_world".

So how should b() be constructed? Thx.

chris97ong
  • 6,870
  • 7
  • 32
  • 52
  • 1
    No, you don't want that. [What problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) are you trying to solve with this? – Bergi Apr 07 '14 at 11:27
  • Try use this http://stackoverflow.com/questions/3178892/get-function-name-in-javascript – Nail Shakirov Apr 07 '14 at 11:30
  • 1
    http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript – Roland Jansen Apr 07 '14 at 11:30

2 Answers2

4

You could use three despised, deprecated and non-standard properties for this:

function b() {
    return arguments.callee.caller.name;
}

Don't expect it to work in older browsers, newer browsers, strict mode, internet explorer, …

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • +1 I was not aware of it. if it a non-standard can we pass the method name as a parameter to `b(theCallerName){ return theCallerName}`? – Praveen Apr 07 '14 at 11:33
  • 1
    Yes, you can and should, though it makes `b()` superfluous :-) – Bergi Apr 07 '14 at 11:34
  • 1
    @Praveen—hopefully you'd pass a reference to the function, rather than just its name. ;-) – RobG Apr 07 '14 at 11:37
  • 1
    @RobG: Actually I meant passing the name as a string is the best solution :-) – Bergi Apr 07 '14 at 11:37
0

There is also a trick with the stack trace, which is also despised (since it's highly platform-dependent) and ugly to say the least:

function getStackTrace() { return new Error().stack; }

Which would return something like this in chrome's developer's console:

"Error
    at getStackTrace (<anonymous>:2:35)
    at <anonymous>:2:1
    at Object.InjectedScript._evaluateOn (<anonymous>:581:39)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:540:52)
    at Object.InjectedScript.evaluate (<anonymous>:459:21)"

and you go with reqular expressions from there.

Will work in Chrome, not sure for others, so it's bad for production-versions. Nice hack though :)