How do you find out the caller function in JavaScript?

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

    If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference:

    function main()
    {
       Hello(this);
    }
    
    function Hello(caller)
    {
        // caller will be the object that called Hello. boom like that... 
        // you can add an undefined check code if the function Hello 
        // will be called without parameters from somewhere else
    }
    

提交回复
热议问题