当启用use strict时,如何在JavaScript中找到调用函数?

时间:2015-04-11 00:00:36

标签: javascript use-strict

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




5 个答案:

答案 0 :(得分:38)

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

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

'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中对此进行了测试,因此您的里程可能会有所不同。

答案 1 :(得分:25)

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

@ 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




答案 2 :(得分:6)

它对我不起作用 这是我最终做的事情,以防它有助于某人

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);
}

答案 3 :(得分:4)

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

console.trace()

但是如果您需要与调用者进行某些操作,这可能没有用。

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

答案 4 :(得分:0)

  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
  }