在严格模式下获取当前函数名称

时间:2016-07-18 11:22:32

标签: javascript strict

我需要将当前函数名称作为字符串来登录我们的日志工具。但arguments.callee.name仅适用于松散模式。如何获取"use strict"下的函数名称?

5 个答案:

答案 0 :(得分:30)

为了记录/调试,您可以在记录器中创建一个新的Error对象并检查其.stack属性,例如



function logIt(message) {
    var stack = new Error().stack,
        caller = stack.split('\n')[2].trim();
    console.log(caller + ":" + message);
}

function a(b) {
    b()
}

a(function xyz() {
    logIt('hello');
});




答案 1 :(得分:3)

您可以将函数绑定为其上下文,然后您可以通过this.name属性访问其名称:

function x(){
  console.log(this.name);
}
x.bind(x)();

答案 2 :(得分:1)

以@georg 解决方案为基础,此解决方案仅返回函数名称。请注意,如果从匿名函数调用它可能会失败

function getFncName() {
    const stackLine = (new Error())!.stack!.split('\n')[2].trim()
    const fncName = stackLine.match(/at Object.([^ ]+)/)?.[1]
    return fncName
}

function Foo() {
    console.log(getFncName()) // prints 'Foo'
}

答案 3 :(得分:0)

经过一番研究后,这是一个很好的解决方案:

function getFnName(fn) {
  var f = typeof fn == 'function';
  var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
  return (!f && 'not a function') || (s && s[1] || 'anonymous');
}



function test(){
    console.log(getFnName(this));
}

test  = test.bind(test);

test(); // 'test'

来源:https://gist.github.com/dfkaye/6384439

答案 4 :(得分:0)

动态检索函数名称(如魔术变量)的一个简单解决方案是使用作用域变量和 Function.name 属性。

{
  function foo() {
    alert (a.name);
  }; let a = foo
}
{
  function foo2() {
    alert(a.name)
  }; let a = foo2
};
foo();//logs foo
foo2();//logs foo2

注意:嵌套函数不再是源元素,因此不会被提升。此外,这种技术不能用于匿名函数。

相关问题