首頁  >  文章  >  web前端  >  如何在 JavaScript 中檢索函數的名稱?

如何在 JavaScript 中檢索函數的名稱?

DDD
DDD原創
2024-10-26 05:42:03435瀏覽

How Can You Retrieve a Function's Name in JavaScript?

存取作用域內的函數名稱

從函數本身內部檢索函數名稱的能力是 JavaScript 中的有用技術。然而,這可能具有挑戰性,因為從內部存取函數名稱時不容易獲得它們。

ES6 解:

在ES6 中,存取函數名稱很簡單:

<code class="javascript">const getFunctionName = () => myFunction.name;</code>

ES5 解:

對於ES5,建議使用以下方法:

<code class="javascript">function getFunctionName(func) {
  const funcStr = func.toString();
  const name = funcStr.substring('function '.length, funcStr.indexOf('('));
  return name;
}</code>

使用Function.caller (不建議):

Function.caller 提供了存取呼叫者姓名的非標準解決方案。但是,由於潛在的兼容性問題及其在嚴格模式下的棄用,應該避免使用它。

基於正規表示式的解:

另一個高效率的ES5 方法涉及使用正規表示式:

<code class="javascript">const getFunctionName = (func) => /function\s+([a-zA-Z$][a-zA-Z$0-9]+)/.exec(func.toString())[1];</code>

範例:

讓我們使用提供的程式碼片段作為範例:

<code class="javascript">var ns.parent = function() {
  // at this point, i want to know who the child is that called the parent
  // ie
  console.log(getFunctionName(this));
}

var obj = new ns.parent.child();</code>

這將輸出:「newFunc」因為newFunc是呼叫父函數的函數。

以上是如何在 JavaScript 中檢索函數的名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn