How do you find out the caller function in JavaScript?

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

    In both ES6 and Strict mode, use the following to get the Caller function

    console.log((new Error()).stack.split("\n")[2].trim().split(" ")[1])
    

    Please note that, the above line will throw an exception, if there is no caller or no previous stack. Use accordingly.

    To get callee (the current function name), use:

    console.log((new Error()).stack.split("\n")[1].trim().split(" ")[1]) 
    

提交回复
热议问题