anjanesh
anjanesh

Reputation: 4251

function caller name in an anonymous function

Im guessing there is no way to get the function caller name in an anonymous function, is there ?

(function()
{
    var cls = function()
    {
        this.foo = function()
        {
            console.log(arguments.callee.caller); // null
            foo1();
        }

        var foo1 = function()
        {
            console.log(arguments.callee.caller); // foo
            foo2();
        }

        var foo2 = function()
        {
            console.log(arguments.callee.caller); // foo1
            cls.foo(); // local
        }

        var cls =
        {
            foo : function()
            {
                console.log(arguments.callee.caller); // cls.foo2
            }
        }
    }
    return (window.cls = cls);
})();

var c1 = new cls();
c1.foo();

Upvotes: 5

Views: 5290

Answers (2)

Lightbeard
Lightbeard

Reputation: 4131

It is possible in recent versions of Chrome and Firefox as follows. I only recommend this for debugging purposes (e.g. javascript tracing in non-production)

var mystery = function() {
   var myNameInChrome = /.*Object\.(.*)\s\(/.exec(new Error().stack)[1];
   var myNameInFF = new Error().stack.split("@")[0];
}

Upvotes: 1

Dean Burge
Dean Burge

Reputation: 3461

Correct - they're anonymous. If you need to know their names by callee, you'll need to give them a name. Will something like this.foo = function foo() rather than this.foo = function() work for you?

Upvotes: 4

Related Questions