最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - function caller name in an anonymous function - Stack Overflow

programmeradmin13浏览0评论

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();

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();
Share Improve this question edited Dec 27, 2010 at 10:10 anjanesh asked Dec 27, 2010 at 9:56 anjaneshanjanesh 4,2719 gold badges52 silver badges74 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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?

It is possible in recent versions of Chrome and Firefox as follows. I only remend 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];
}
发布评论

评论列表(0)

  1. 暂无评论