function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

有办法找到调用堆栈吗?


当前回答

使用严格模式开/关(JavaScript & TypeScript),如果(!)调用者存在,你可以尝试这个

console.log(`caller:${(new Error()).stack?.split('\n')[2].trim().split(' ')[1]}`)

其他回答

概括一下(并说得更清楚)…

这段代码:

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

等价于:

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

显然,第一部分更容易移植,因为你可以改变函数的名字,从“Hello”说成“Ciao”,但仍然可以让整个程序正常工作。

在后一种情况下,如果你决定重构被调用函数的名称(Hello),你将不得不改变它的所有出现:

你可以使用函数。调用方获取调用函数。旧的方法使用参数。Caller被认为是过时的。

下面的代码说明了它的用法:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

关于废参数的注释。打电话者:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

功能。呼叫方为非标准:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

试着访问这个:

arguments.callee.caller.name

据我所知,我们有两种方法从给定的资源中得到

arguments.caller whoCalled()函数 { 如果参数。Caller == null) console.log('我是从全局作用域调用的。'); 其他的 console.log(参数。Caller + '打电话给我!'); } Function.caller myFunc()函数 { 如果(myFunc。调用者== null) { 返回'函数是从顶部调用的!'; } 其他的 { 返回'这个函数的调用者是' + myfuncc .caller; } }

我想你已经有答案了:)。

由于之前的答案都不像我所寻找的那样(只得到最后一个函数调用者,而不是作为字符串或callstack的函数),我在这里为那些像我一样的人发布了我的解决方案,希望这对他们有用:

function getCallerName(func) { if (!func) return "anonymous"; let caller = func.caller; if (!caller) return "anonymous"; caller = caller.toString(); if (!caller.trim().startsWith("function")) return "anonymous"; return caller.substring(0, caller.indexOf("(")).replace("function",""); } // Example of how to use "getCallerName" function function Hello(){ console.log("ex1 => " + getCallerName(Hello)); } function Main(){ Hello(); // another example console.log("ex3 => " + getCallerName(Main)); } Main();