function main()
{
   Hello();
}

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

有办法找到调用堆栈吗?


当前回答

只需控制台日志错误堆栈。这样你就可以知道你是如何被召唤的

Const hello = () => { console.log(新的错误('I was called').stack) } Const sello = () => { 你好() } 你可以()

其他回答

使用严格模式开/关(JavaScript & TypeScript),如果(!)调用者存在,你可以尝试这个

console.log(`caller:${(new Error()).stack?.split('\n')[2].trim().split(' ')[1]}`)

只是想让你知道,在PhoneGap/Android上,这个名字似乎不工作。但是arguments.callee.caller.toString()可以做到这一点。

试着访问这个:

arguments.callee.caller.name

2018年更新

严格模式下禁止调用。下面是使用(非标准)错误堆栈的替代方案。

下面的函数似乎在Firefox 52和Chrome 61-71中完成了这项工作,尽管它的实现对这两种浏览器的日志格式做了很多假设,应该谨慎使用,因为它会抛出一个异常,并可能在完成之前执行两个正则表达式匹配。

'use strict'; const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/; function fnName(str) { const regexResult = fnNameMatcher.exec(str); return regexResult[1] || regexResult[2]; } function log(...messages) { const logLines = (new Error().stack).split('\n'); const callerName = fnName(logLines[1]); if (callerName !== null) { if (callerName !== 'log') { console.log(callerName, 'called log with:', ...messages); } else { console.log(fnName(logLines[2]), 'called log with:', ...messages); } } else { console.log(...messages); } } function foo() { log('hi', 'there'); } (function main() { foo(); }());

我认为下面的代码段可能会有帮助:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

执行以下代码:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

function fnBsnCallStack1() {
    fnPureLog('Stock Count', 100)
}

function fnBsnCallStack2() {
    fnBsnCallStack1()
}

fnBsnCallStack2();

日志是这样的:

Call Stack:
    at window.fnPureLog (<anonymous>:8:27)
    at fnBsnCallStack1 (<anonymous>:13:5)
    at fnBsnCallStack2 (<anonymous>:17:5)
    at <anonymous>:20:1 
Stock Count: 100