How do you find out the caller function in JavaScript?

前端 未结 30 1953
粉色の甜心
粉色の甜心 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

    heystewart's answer and JiarongWu's answer both mentioned that the Error object has access to the stack.

    Here's an example:

    function main() {
      Hello();
    }
    
    function Hello() {
      var stack = new Error().stack;
      // N.B. stack === "Error\n  at Hello ...\n  at main ... \n...."
      var m = stack.match(/.*?Hello.*?\n(.*?)\n/);
      if (m) {
        var caller_name = m[1];
        console.log("Caller is:", caller_name)
      }
    }
    
    main();

    Different browsers shows the stack in different string formats:

    Safari  : Caller is: main@https://stacksnippets.net/js:14:8
    Firefox : Caller is: main@https://stacksnippets.net/js:14:3
    Chrome  : Caller is:     at main (https://stacksnippets.net/js:14:3)
    IE Edge : Caller is:    at main (https://stacksnippets.net/js:14:3)
    IE      : Caller is:    at main (https://stacksnippets.net/js:14:3)
    

    Most browsers will set the stack with var stack = (new Error()).stack. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.

    Conclusion: It's possible to determine "main" is the caller to "Hello" using the stack in the Error object. In fact it will work in cases where the callee / caller approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.

提交回复
热议问题