tes*_*dtv 11 javascript firebug dom-events
我在JS中有一个函数,它从多个地方调用.
现在我在iPad上测试这个页面,因此发现调试有点困难.
我可以通过某种方式(在控制台上打印)从我的函数调用的位置找到吗?
Jam*_*mes 16
像这样?
function testOne() {
console.log("Test 1");
logTest();
}
function testTwo() {
console.log("Test 2");
logTest();
}
function logTest() {
console.log("Being called from " + arguments.callee.caller.toString());
}
testOne();
testTwo();
Run Code Online (Sandbox Code Playgroud)
如果您'use strict';在JavaScript文件中使用,则需要注释/删除它,否则您将获得以下内容:
未捕获的TypeError:严格模式函数或调用它们的参数对象可能无法访问'caller','callee'和'arguments'属性
Squ*_*eet 12
我喜欢使用的一种简单方法是arguments.callee.caller.name.
假设你想知道调用名为myFunction的函数是什么:
function myFunction() {
console.log(arguments.callee.caller.name);
/* Other stuff... */
}
Run Code Online (Sandbox Code Playgroud)
但是,浏览器对此的支持并不是那么好,所以你可以使用arguments.callee.caller.toString()代替.请注意,这将返回调用myFunction的函数的内容,因此您需要自己挖掘函数名称.
或者,你可以使用这样一个很好的堆栈跟踪函数:
function getStack(){
fnRE = /function\s*([\w\-$]+)?\s*\(/i;
var caller = arguments.callee.caller;
var stack = "Stack = ";
var fn;
while (caller){
fn = fnRE.test(caller.toString()) ? RegExp.$1 || "{?}" : "{?}";
stack += "-->"+fn;
caller = caller.arguments.callee.caller;
};
return stack;
}
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪通过http://www.amirharel.com/2010/01/25/using-caller-and-callee-for-stack-trace/