How do you find out the caller function in JavaScript?

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

    To recap (and make it clearer) ...

    this code:

    function Hello() {
        alert("caller is " + arguments.callee.caller.toString());
    }
    

    is equivalent to this:

    function Hello() {
        alert("caller is " + Hello.caller.toString());
    }
    

    Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

    In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(

提交回复
热议问题