【发布时间】:2011-06-07 22:44:26
【问题描述】:
Firebug 能够记录对特定函数名称的调用。我正在寻找一个有时会阻止页面呈现但不会导致任何错误或警告的错误。该错误仅出现大约一半的时间。那么如何获取整个程序的所有函数调用列表,或者整个程序执行的某种堆栈跟踪?
【问题讨论】:
标签: javascript firebug
Firebug 能够记录对特定函数名称的调用。我正在寻找一个有时会阻止页面呈现但不会导致任何错误或警告的错误。该错误仅出现大约一半的时间。那么如何获取整个程序的所有函数调用列表,或者整个程序执行的某种堆栈跟踪?
【问题讨论】:
标签: javascript firebug
试试这个:
console.trace()
我不知道是不是所有浏览器都支持,所以我先检查一下是否存在。
【讨论】:
Firefox provides console.trace() 打印调用堆栈非常方便。它也可用于Chrome 和IE 11。
或者尝试这样的事情:
function print_call_stack() {
var stack = new Error().stack;
console.log("PRINTING CALL STACK");
console.log( stack );
}
【讨论】:
我在没有萤火虫的情况下完成了这个。在 chrome 和 firefox 中测试:
console.error("I'm debugging this code.");
在您的程序将其打印到控制台后,您可以单击它的小箭头以展开调用堆栈。
【讨论】:
当我需要堆栈跟踪时,我会执行以下操作,也许您可以从中汲取一些灵感:
function logStackTrace(levels) {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox / chrome
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
callstack.push(lines[i]);
}
//Remove call to logStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
else if (window.opera && e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += " at " + lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to logStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
if (levels) {
console.log(callstack.slice(0, levels).join('\n'));
}
else {
console.log(callstack.join('\n'));
}
};
版主说明:此答案中的代码似乎也出现在this post from Eric Wenderlin's blog 中。但是,此答案的作者声称它是他自己的代码,是在此处链接的博客文章之前编写的。出于善意,我已将链接添加到帖子和此注释。
【讨论】:
尝试一次通过一行或一个函数单步执行您的代码,以确定它在哪里停止正常工作。或者做一些合理的猜测,并在你的代码中分散日志语句。
【讨论】:
console.log('something') 语句,看看哪些是(和不是)被调用