1

Here is my code:

var structure = {
A: function() {
    this.B();
},

B: function() {
      console.log(arguments.callee.caller.toString());
}

};

Then I run:

structure.A();

As you understand, I'm trying to get caller function name, but result is empty string. Are any ideas how to do that?

TK-95
  • 1,141
  • 2
  • 10
  • 21
  • 3
    Well, both functions don't have names. The property name is technically not the name of the function. Related: http://stackoverflow.com/q/17557957/218196 . But the question is: Why are trying to do this? What problem are you trying to solve? – Felix Kling Jul 11 '15 at 17:31
  • I guess the OP just indeed wants `arguments.callee.caller.toString()` to returns `A` when he calls `structure.B()`. Is that correct, @snith ? – TaoPR Jul 11 '15 at 17:36
  • 1
    The simplest solution would be to give the functions names: `A: function A() { ... }`. – Felix Kling Jul 11 '15 at 17:39
  • 1
    Note that `arguments.callee` should not be used in any serious production work. It won't work in strict mode, and would very probably also fail in the upcoming ES6 standard. – light Jul 11 '15 at 17:43
  • Great , it's almost the solution, I will keep it in mind. But still actual. Can I get name of caller without renaming? – TK-95 Jul 11 '15 at 17:46
  • You need to work with non-anonymous functions if you want to keep track of the call stack, and since you are barking up the deprecation tree it might be worth looking at this somewhat related question [here](http://stackoverflow.com/questions/15557487/argument-callee-name-alternative-in-the-new-ecma5-javascript-standard). – rgbchris Jul 11 '15 at 18:01

1 Answers1

0

I've added the function name A, and slightly changed the statement that gets the string to print. Does this do what you want?

var structure = {
    A: function A() {
        this.B();
    },
    B: function() {
        console.log(arguments.callee.caller.name);
    }
}

structure.A();
Iain
  • 328
  • 2
  • 12
  • Can I get same result without renaming? – TK-95 Jul 11 '15 at 17:49
  • I do not believe so. There could be any number of variables your anonymous function is assigned to, the function needs to have its own name if you wish to get it. Why are you trying to do this? Perhaps you could consider a different approach, that avoids this situation entirely? – Iain Jul 11 '15 at 18:05