How do you find out the caller function in JavaScript?

前端 未结 30 1502
粉色の甜心
粉色の甜心 2020-11-21 17:46
function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is \'main\'?
}

Is there a way to find out the call

30条回答
  •  执念已碎
    2020-11-21 18:05

    Why all of the solutions above look like a rocket science. Meanwhile, it should not be more complicated than this snippet. All credits to this guy

    How do you find out the caller function in JavaScript?

    var stackTrace = function() {
    
        var calls = [];
        var caller = arguments.callee.caller;
    
        for (var k = 0; k < 10; k++) {
            if (caller) {
                calls.push(caller);
                caller = caller.caller;
            }
        }
    
        return calls;
    };
    
    // when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content
    // [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]
    

提交回复
热议问题