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'?
}
有办法找到调用堆栈吗?
当前回答
我会这样做:
function Hello() {
console.trace();
}
其他回答
我知道你提到了“在Javascript中”,但如果目的是调试,我认为使用浏览器的开发工具更容易。这是它在Chrome中的样子: 只需将调试器放置在您想要研究堆栈的位置。
为什么上面所有的解决方案看起来都像火箭科学。同时,它不应该比这段代码更复杂。都要归功于这个家伙
如何在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)]
在这里,除了函数名之外的所有内容都被RegExp从caller.toString()中剥离。
<!DOCTYPE html>
<meta charset="UTF-8">
<title>Show the callers name</title><!-- This validates as html5! -->
<script>
main();
function main() { Hello(); }
function Hello(){
var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
name = name.replace(/\s/g,'');
if ( typeof window[name] !== 'function' )
alert ("sorry, the type of "+name+" is "+ typeof window[name]);
else
alert ("The name of the "+typeof window[name]+" that called is "+name);
}
</script>
我试图用这个问题来解决这个问题和当前的奖励。
赏金要求在严格模式下获得调用者,我能看到的唯一方法是引用在严格模式外声明的函数。
例如,以下是非标准的,但已经用之前(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 ();
下面是一个函数来获得完整的stacktrace:
function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
stack += '\n' + f.name;
f = f.caller;
}
return stack;
}