function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

有办法找到调用堆栈吗?


当前回答

function Hello() {
    alert(Hello.caller);
}

其他回答

为什么上面所有的解决方案看起来都像火箭科学。同时,它不应该比这段代码更复杂。都要归功于这个家伙

如何在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)]
function Hello() {
    alert(Hello.caller);
}

使用*arguments.callee更安全。调用自参数。不赞成调用…

在这里,除了函数名之外的所有内容都被RegExp从caller.toString()中剥离。

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Show the callers name</title><!-- This validates as html5! -->
<script>
main();
function main() { Hello(); }
function Hello(){
  var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
  name = name.replace(/\s/g,'');
  if ( typeof window[name] !== 'function' )
    alert ("sorry, the type of "+name+" is "+ typeof window[name]);
  else
    alert ("The name of the "+typeof window[name]+" that called is "+name);
}
</script>

注意,根据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());
}