Function Caller Name in Anonymous Function

I assume there is no way to get the caller name of a function 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();
+3
source share
2 answers

That's right - they are anonymous. If you need to know their names on call, you will need to give them a name. Will something like this.foo = function foo(), and not, work this.foo = function()?

+3
source

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

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

Source: https://habr.com/ru/post/1782258/


All Articles