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.

3

2 Answers 2

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, …

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

4 Comments

+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}?
Yes, you can and should, though it makes b() superfluous :-)
@Praveen—hopefully you'd pass a reference to the function, rather than just its name. ;-)
@RobG: Actually I meant passing the name as a string is the best solution :-)
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 :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.