How do you find out the caller function in JavaScript?

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

    As far as I know, we have 2 way for this from given sources like this-

    1. arguments.caller

      function whoCalled()
      {
          if (arguments.caller == null)
             console.log('I was called from the global scope.');
          else
             console.log(arguments.caller + ' called me!');
      }
      
    2. Function.caller

      function myFunc()
      {
         if (myFunc.caller == null) {
            return 'The function was called from the top!';
         }
         else
         {
            return 'This function\'s caller was ' + myFunc.caller;
          }
      }
      

    Think u have your answer :).

提交回复
热议问题