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'?
}
有办法找到调用堆栈吗?
当前回答
使用严格模式开/关(JavaScript & TypeScript),如果(!)调用者存在,你可以尝试这个
console.log(`caller:${(new Error()).stack?.split('\n')[2].trim().split(' ')[1]}`)
其他回答
概括一下(并说得更清楚)…
这段代码:
function Hello() {
alert("caller is " + arguments.callee.caller.toString());
}
等价于:
function Hello() {
alert("caller is " + Hello.caller.toString());
}
显然,第一部分更容易移植,因为你可以改变函数的名字,从“Hello”说成“Ciao”,但仍然可以让整个程序正常工作。
在后一种情况下,如果你决定重构被调用函数的名称(Hello),你将不得不改变它的所有出现:
为什么上面所有的解决方案看起来都像火箭科学。同时,它不应该比这段代码更复杂。都要归功于这个家伙
如何在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)]
由于之前的答案都不像我所寻找的那样(只得到最后一个函数调用者,而不是作为字符串或callstack的函数),我在这里为那些像我一样的人发布了我的解决方案,希望这对他们有用:
function getCallerName(func) { if (!func) return "anonymous"; let caller = func.caller; if (!caller) return "anonymous"; caller = caller.toString(); if (!caller.trim().startsWith("function")) return "anonymous"; return caller.substring(0, caller.indexOf("(")).replace("function",""); } // Example of how to use "getCallerName" function function Hello(){ console.log("ex1 => " + getCallerName(Hello)); } function Main(){ Hello(); // another example console.log("ex3 => " + getCallerName(Main)); } Main();
function Hello() {
alert(Hello.caller);
}
如果你不打算在IE < 11中运行它,那么console.trace()将适合。
function main() {
Hello();
}
function Hello() {
console.trace()
}
main()
// Hello @ VM261:9
// main @ VM261:4