启用 use strict 后,如何找出 JavaScript 中的调用函数?

How do you find out the caller function in JavaScript when use strict is enabled?

是否可以在启用 use strict 时查看函数的 callee/caller?

'use strict';

function jamie (){
    console.info(arguments.callee.caller.name);
    //this will output the below error
    //uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
};

function jiminyCricket (){
   jamie();
}

jiminyCricket ();

对于它的价值,我同意上面的评论。无论您要解决什么问题,通常都有更好的解决方案。

但是,仅出于说明目的,这里有一个(非常难看)的解决方案:

'use strict'

function jamie (){
    var callerName;
    try { throw new Error(); }
    catch (e) { 
        var re = /(\w+)@|at (\w+) \(/g, st = e.stack, m;
        re.exec(st), m = re.exec(st);
        callerName = m[1] || m[2];
    }
    console.log(callerName);
};

function jiminyCricket (){
   jamie();
}

jiminyCricket(); // jiminyCricket

我只在 Chrome、Firefox 和 IE11 中对此进行了测试,因此您的情况可能会有所不同。

请注意,这不应在生产中使用。这是一个丑陋的解决方案,对调试很有帮助,但如果您需要调用者提供一些东西,请将其作为参数传递或将其保存到可访问的变量中。

@p.s.w.g答案的简短版本(不抛出错误,只是实例化一个):

    let re = /([^(]+)@|at ([^(]+) \(/g;
    let aRegexResult = re.exec(new Error().stack);
    sCallerName = aRegexResult[1] || aRegexResult[2];

完整代码段:

'use strict'

function jamie (){
    var sCallerName;
    {
        let re = /([^(]+)@|at ([^(]+) \(/g;
        let aRegexResult = re.exec(new Error().stack);
        sCallerName = aRegexResult[1] || aRegexResult[2];
    }
    console.log(sCallerName);
};

function jiminyCricket(){
   jamie();
};

jiminyCricket(); // jiminyCricket

它对我不起作用 这是我最后做的,以防万一它能帮助别人

function callerName() {
  try {
    throw new Error();
  }
  catch (e) {
    try {
      return e.stack.split('at ')[3].split(' ')[0];
    } catch (e) {
      return '';
    }
  }

}
function currentFunction(){
  let whoCallMe = callerName();
  console.log(whoCallMe);
}

您可以使用以下方法获取堆栈跟踪:

console.trace()

但如果您需要对来电者做某事,这可能没有用。

https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

  functionName() {
    return new Error().stack.match(/ at (\S+)/g)[1].get(/ at (.+)/);
  }

  // Get - extract regex
  String.prototype.get = function(pattern, defaultValue = "") {
    if(pattern.test(this)) {
      var match = this.match(pattern);
      return match[1] || match[0];
    }
    return defaultValue; // if nothing is found, the answer is known, so it's not null
  }