How do you find out the caller function in JavaScript?

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

    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

提交回复
热议问题