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'?
}
有办法找到调用堆栈吗?
当前回答
我试图用这个问题来解决这个问题和当前的奖励。
赏金要求在严格模式下获得调用者,我能看到的唯一方法是引用在严格模式外声明的函数。
例如,以下是非标准的,但已经用之前(2016年3月29日)和当前(2018年8月1日)版本的Chrome、Edge和Firefox进行了测试。
函数调用者() { 返回caller.caller.caller; } 使用严格的; main()函数 { //原来的问题: 你好(); //赏金问题: (function() {console.log('匿名函数调用' + caller().name);}) (); } 函数Hello () { //你如何发现调用函数是'main'? console.log('Hello calling by ' + caller().name); } main ();
其他回答
为什么上面所有的解决方案看起来都像火箭科学。同时,它不应该比这段代码更复杂。都要归功于这个家伙
如何在JavaScript中找到调用者函数?
var stackTrace = function() {
var calls = [];
var caller = arguments.callee.caller;
for (var k = 0; k < 10; k++) {
if (caller) {
calls.push(caller);
caller = caller.caller;
}
}
return calls;
};
// when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content
// [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]
使用*arguments.callee更安全。调用自参数。不赞成调用…
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(); }());
我知道你提到了“在Javascript中”,但如果目的是调试,我认为使用浏览器的开发工具更容易。这是它在Chrome中的样子: 只需将调试器放置在您想要研究堆栈的位置。
如果你只想要函数名而不是代码,并且想要一个独立于浏览器的解决方案,请使用以下方法:
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]);