53

启用时是否可以看到函数的被调用者/调用者use strict

'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 ();

4

5 回答 5

51

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

但是,仅出于说明目的,这是一个(非常丑陋的)解决方案:

'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 中测试过这个,所以你的里程可能会有所不同。

于 2015-04-11T00:17:01.323 回答
33

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

@pswg 答案的简短版本(没有抛出错误,只是实例化一个):

    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

于 2016-03-22T10:48:02.060 回答
12

它对我不起作用这是我最终要做的,以防万一它对某人有所帮助

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);
}
于 2017-06-05T10:12:13.210 回答
6

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

console.trace()

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

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

于 2019-02-13T13:24:57.887 回答
-1
  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
  }
于 2020-05-19T23:18:12.310 回答