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中找到调用者函数?
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)]
其他回答
注意,根据MDN文档,此解决方案已弃用,不应再使用
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
function Hello()
{
alert("caller is " + Hello.caller);
}
注意,这个特性不是标准的,来自Function.caller:
非标准的 这个特性是非标准的,不在标准轨道上。不要在面向Web的生产站点上使用它:它并不适用于每个用户。实现之间也可能存在很大的不兼容性,将来行为可能会发生变化。
以下是2008年的旧答案,在现代Javascript中不再支持:
function Hello()
{
alert("caller is " + arguments.callee.caller.toString());
}
概括一下(并说得更清楚)…
这段代码:
function Hello() {
alert("caller is " + arguments.callee.caller.toString());
}
等价于:
function Hello() {
alert("caller is " + Hello.caller.toString());
}
显然,第一部分更容易移植,因为你可以改变函数的名字,从“Hello”说成“Ciao”,但仍然可以让整个程序正常工作。
在后一种情况下,如果你决定重构被调用函数的名称(Hello),你将不得不改变它的所有出现:
如果你出于某种原因真的需要这个功能,希望它能跨浏览器兼容,不担心严格的东西,并且向前兼容,那么传递一个this引用:
function main()
{
Hello(this);
}
function Hello(caller)
{
// caller will be the object that called Hello. boom like that...
// you can add an undefined check code if the function Hello
// will be called without parameters from somewhere else
}
解决这个问题的另一种方法是简单地将调用函数的名称作为参数传递。
例如:
function reformatString(string, callerName) {
if (callerName === "uid") {
string = string.toUpperCase();
}
return string;
}
现在,你可以这样调用这个函数:
function uid(){
var myString = "apples";
reformatString(myString, function.name);
}
我的示例使用了对函数名的硬编码检查,但是您可以轻松地使用switch语句或其他逻辑来完成您想要的操作。
为什么上面所有的解决方案看起来都像火箭科学。同时,它不应该比这段代码更复杂。都要归功于这个家伙
如何在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)]