function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
有办法找到调用堆栈吗?
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]}`)
其他回答
使用*arguments.callee更安全。调用自参数。不赞成调用…
如果你只想要函数名而不是代码,并且想要一个独立于浏览器的解决方案,请使用以下方法:
var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];
注意,如果数组中没有[1]元素,那么上面的代码将返回错误。要解决这个问题,请使用以下方法:
var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);
下面是一个函数来获得完整的stacktrace:
function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
stack += '\n' + f.name;
f = f.caller;
}
return stack;
}
heystewart和JiarongWu的回答都提到了Error对象可以访问堆栈。
这里有一个例子:
函数main() { 你好(); } 函数Hello() { 尝试{ throw new Error(); } catch (err) { Let stack = err.stack; // N.B. stack === "Error\n at Hello…\n at main…\ n……” let m = stack.match(/.*?Hello.*?\n(.*?)\n/); 如果(m) { 让caller_name = m[1]; console.log("Caller is:", caller_name); } } } main ();
不同的浏览器以不同的字符串格式显示堆栈:
Safari : Caller is: main@https://stacksnippets.net/js:14:8
Firefox : Caller is: main@https://stacksnippets.net/js:14:3
Chrome : Caller is: at main (https://stacksnippets.net/js:14:3)
IE Edge : Caller is: at main (https://stacksnippets.net/js:14:3)
IE : Caller is: at main (https://stacksnippets.net/js:14:3)
大多数浏览器会使用var stack = (new Error()).stack来设置堆栈。在Internet Explorer中,堆栈是未定义的——你必须抛出一个真正的异常来检索堆栈。
结论:使用Error对象中的堆栈可以确定“main”是“Hello”的调用者。事实上,它可以在被调用方/调用方方法不起作用的情况下工作。它还会显示上下文,即源文件和行号。然而,要使解决方案跨平台还需要努力。
2018年更新
严格模式下禁止调用。下面是使用(非标准)错误堆栈的替代方案。
下面的函数似乎在Firefox 52和Chrome 61-71中完成了这项工作,尽管它的实现对这两种浏览器的日志格式做了很多假设,应该谨慎使用,因为它会抛出一个异常,并可能在完成之前执行两个正则表达式匹配。
'use strict'; const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/; function fnName(str) { const regexResult = fnNameMatcher.exec(str); return regexResult[1] || regexResult[2]; } function log(...messages) { const logLines = (new Error().stack).split('\n'); const callerName = fnName(logLines[1]); if (callerName !== null) { if (callerName !== 'log') { console.log(callerName, 'called log with:', ...messages); } else { console.log(fnName(logLines[2]), 'called log with:', ...messages); } } else { console.log(...messages); } } function foo() { log('hi', 'there'); } (function main() { foo(); }());