How do you find out the caller function in JavaScript?

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

    I think the following code piece may be helpful:

    window.fnPureLog = function(sStatement, anyVariable) {
        if (arguments.length < 1) { 
            throw new Error('Arguments sStatement and anyVariable are expected'); 
        }
        if (typeof sStatement !== 'string') { 
            throw new Error('The type of sStatement is not match, please use string');
        }
        var oCallStackTrack = new Error();
        console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
    }
    

    Execute the code:

    window.fnPureLog = function(sStatement, anyVariable) {
        if (arguments.length < 1) { 
            throw new Error('Arguments sStatement and anyVariable are expected'); 
        }
        if (typeof sStatement !== 'string') { 
            throw new Error('The type of sStatement is not match, please use string');
        }
        var oCallStackTrack = new Error();
        console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
    }
    
    function fnBsnCallStack1() {
        fnPureLog('Stock Count', 100)
    }
    
    function fnBsnCallStack2() {
        fnBsnCallStack1()
    }
    
    fnBsnCallStack2();
    

    The log looks like this:

    Call Stack:
        at window.fnPureLog (:8:27)
        at fnBsnCallStack1 (:13:5)
        at fnBsnCallStack2 (:17:5)
        at :20:1 
    Stock Count: 100
    

提交回复
热议问题