How do you find out the caller function in JavaScr

2018-12-31 02:55发布

function main()
{
   Hello();
}

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

Is there a way to find out the call stack at all?

29条回答
情到深处是孤独
2楼-- · 2018-12-31 03:34
function Hello() {
    alert(Hello.caller);
}
查看更多
不流泪的眼
3楼-- · 2018-12-31 03:34

Just console log your error stack. You can then know how are you being called

const hello = () => {
  console.log(new Error('I was called').stack)
}

const sello = () => {
  hello()
}

sello()

查看更多
素衣白纱
4楼-- · 2018-12-31 03:35

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)]
查看更多
骚的不知所云
5楼-- · 2018-12-31 03:42

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...

查看更多
美炸的是我
6楼-- · 2018-12-31 03:43

You can use Function.Caller to get the calling function. The old method using argument.caller is considered obsolete.

The following code illustrates its use:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

Notes about obsolete argument.caller: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

Be aware Function.caller is non-standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

查看更多
登录 后发表回答