How do you find out the caller function in JavaScript?

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

    I'm attempting to address both the question and the current bounty with this question.

    The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.

    For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.

    function caller()
    {
       return caller.caller.caller;
    }
    
    'use strict';
    function main()
    {
       // Original question:
       Hello();
       // Bounty question:
       (function() { console.log('Anonymous function called by ' + caller().name); })();
    }
    
    function Hello()
    {
       // How do you find out the caller function is 'main'?
       console.log('Hello called by ' + caller().name);
    }
    
    main();

提交回复
热议问题