How do you find out the caller function in JavaScript?

前端 未结 30 1578
粉色の甜心
粉色の甜心 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 17:58

    If you just want the function name and not the code, and want a browser-independent solution, use the following:

    var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];
    

    Note that the above will return an error if there is no caller function as there is no [1] element in the array. To work around, use the below:

    var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);
    

提交回复
热议问题