How do you find out the caller function in JavaScript?

前端 未结 30 1575
粉色の甜心
粉色の甜心 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 18:07

    Another way around this problem is to simply pass the name of the calling function as a parameter.

    For example:

    function reformatString(string, callerName) {
    
        if (callerName === "uid") {
            string = string.toUpperCase();
        }
    
        return string;
    }
    

    Now, you could call the function like this:

    function uid(){
        var myString = "apples";
    
        reformatString(myString, function.name);
    }
    

    My example uses a hard coded check of the function name, but you could easily use a switch statement or some other logic to do what you want there.

提交回复
热议问题