当启用使用严格时,你如何找出 JavaScript 中的调用者函数



启用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 ();

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

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

'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
  }

最新更新