假设我想获取某种堆栈跟踪信息,以获取在当前函数之前被调用的所有函数的名称。
我做这样的事情:
var callee;
var caller;
var _args = arguments;
var check = 0;
do {
check++;
callee = _args.callee;
caller = callee.caller;
var msg = 'Check ' + check + ' - ' + callee.name
+ ' has been called by: ' + caller.name;
console.log(msg);
if (caller) {
// Get this caller's arguments
_args = caller.arguments;
} else {
reached_end = true;
}
} while (!reached_end);
在大多数情况下,这都可以正常工作。但是有时它陷入无限循环,我想知道:这怎么可能?那我该怎么办?
这是我的无限循环的输出:
Check 1 - __parent__ has been called by: add
Check 2 - add has been called by: afterComponentStartup
Check 3 - afterComponentStartup has been called by: _launchComponents [arg0:"startup"]
Check 4 - _launchComponents has been called by: beforeActionNext
Check 5 - beforeActionNext has been called by: beforeAction
Check 6 - beforeAction has been called by: afterComponentInitialize
Check 7 - afterComponentInitialize has been called by: _launchComponents [arg0:"startup"]
Check 8 - _launchComponents has been called by: beforeActionNext
Check 9 - beforeActionNext has been called by: beforeAction
Check 10 - beforeAction has been called by: afterComponentInitialize
Check 11 - afterComponentInitialize has been called by: _launchComponents [arg0:"startup"]
Check 12 - _launchComponents has been called by: beforeActionNext
Check 13 - beforeActionNext has been called by: beforeAction
Check 14 - beforeAction has been called by: afterComponentInitialize
Check 15 - afterComponentInitialize has been called by: _launchComponents [arg0:"startup"]
Check 16 - _launchComponents has been called by: beforeActionNext
Check 17 - beforeActionNext has been called by: beforeAction
Check 18 - beforeAction has been called by: afterComponentInitialize
Check 19 - afterComponentInitialize has been called by: _launchComponents [arg0:"startup"]
Check 20 - _launchComponents has been called by: beforeActionNext
Check 21 - beforeActionNext has been called by: beforeAction
Check 22 - beforeAction has been called by: afterComponentInitialize
Check 23 - afterComponentInitialize has been called by: _launchComponents [arg0:"startup"]
Check 24 - _launchComponents has been called by: beforeActionNext
Check 25 - beforeActionNext has been called by: beforeAction
Check 26 - beforeAction has been called by: afterComponentInitialize
最佳答案
arguments.callee.caller
指向函数引用,在每个调用堆栈中每个函数仅存在一个。
每次调用一个函数时,都会设置caller
属性,这意味着,如果同一个函数在调用堆栈中被多次调用(与递归函数一样),则先前的值将被重置,而caller
将被重置。现在指向自己。这就是导致您无限循环的原因。
因此,在您的算法中,如果到达callee === callee.caller
的位置,则需要中断以免发生这种情况。
关于javascript - 遍历arguments.callee.caller导致无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15582309/