Jeff
Jeff

Reputation: 1800

trouble getting function caller name (arguments.callee.caller not working)

I've read the numerous posts here on stack overflow about how to use

arguments.callee.caller or arguments.callee.caller.toString()

If you do a simple search, you can find a bunch of posts about this.

So, i decided to try this myself! However, I'd like to find the name of the function inside of a javascript object, but it seems to be returning the code inside of the function, instead of the actual function name.

Here is the jsFiddle: http://jsfiddle.net/4Cp5Z/18/.

To summarize, I make a new app, then call app.testFunction. testFunction() calls receiver(), and I'm expecting var name to be equal to testFunction

app = function() {

    this.testFunction = function() {

        this.receiver();

    };

    this.receiver = function() {

        var name = this.receiver.caller.toString();
        // this.receiver.caller.name outputs nothing...

    };
};

Upvotes: 3

Views: 3922

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

None of the functions in your example has a name. They're all anonymous. The variables and/or properties you're assigning them to have names, but the functions do not. For a function to have a true name, there's a name after the function keyword and the opening parenthesis:

// Declaration
function nameIsHere() {
}

// Expression -- but beware of these ("named function expressions"), see below
var f = function nameIsHere() {
};

(Note that IE8 and earlier create two separate functions if you use a named function expression.)

arguments.callee gives you a reference to the function object from within a call to that function, on engines that support it, and if you're not using strict mode. Beware that it carries a significant performance hit (an order of magnitude on some engines), and it is not allowed in strict mode.

arguments.callee.caller gives you a reference to the function that called the current function (if you're not in strict mode). It doesn't give you its name, but instead an actual reference.

Function#toString has no behavior specified in the specification, but on all major desktop browsers, it gives you some representation of the source code of the function. (This is not necessarily true of mobile and niche browsers.) But again, note that this is non-standard, and varies from browser to browser (for instance, some return the source code fairly verbatim, including comments; others return a decompiled representation of their compiled function).

There's a non-standard Function#name property supported in many, but not all, engines, which gives you the true name of the function (if it has one). But again, it has never been standardized, not even in ES5, and your functions don't have names.

Upvotes: 3

Related Questions