【问题标题】:Get the wrapping function name in Javascript [duplicate]在Javascript中获取包装函数名称[重复]
【发布时间】:2021-02-24 02:30:26
【问题描述】:

如何获取代码的包装函数名称?我想在我的项目的许多函数中实现运行时跟踪功能,并且不想自己替换每个函数中的函数名。

function my_function_name() {
  let t0 = performance.now();
  ....
  DEBUG_TRACK_RUNTIME(performance.now() - t0)
}

function DEBUG_TRACK_RUNTIME(runtime) {
  console.log("PROCESS RUNTIME: " + this.caller, Math.round(runtime, 0) + " ms")
}

有没有办法将函数名“my_function_name()”作为字符串获取?


已回答问题。这个解决方案对我很有用。谢谢

function abcd() {
    let t0 = performance.now();
    ...
    DEBUG_TRACK_RUNTIME(arguments.callee.name, performance.now() - t0)
}

function DEBUG_TRACK_RUNTIME(title, runtime) {
    console.log("PROCESS RUNTIME: " + title + "()", Math.round(runtime, 0) + " ms")
}

【问题讨论】:

  • 也许您不应该基于arguments.callee 构建复杂的通用可重用功能。它不会在严格模式下工作。在现代浏览器中,JS 代码总是在模块和类声明中以严格模式运行。

标签: javascript function


【解决方案1】:

使用arguments.calle.name:

function my_function_name() {
  console.log(arguments.callee.name);
}

my_function_name();

【讨论】:

  • 在严格模式下无法工作。
  • 有合适的方法吗?
猜你喜欢
  • 2014-05-19
  • 2014-02-23
  • 2011-06-20
  • 1970-01-01
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多