"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to get function name inside a function in JavaScript?

How to get function name inside a function in JavaScript?

Posted on 2025-04-29
Browse:254

How Can I Get a Function\'s Name Inside the Function Itself in JavaScript?

How to Retrieve the Function's Name Within the Function Itself?

Determining a function's name internally can be useful for debugging or dynamic operations. To achieve this, consider the following methods:

In ES6:

  • Utilizing myFunction.name to access the function name directly.

In ES5:

  • Using Function.caller (non-standard and not recommended): arguments.callee.name.
  • Implementing a custom function:
function functionName(fun) {
  const ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}
  • Employing a regex pattern, as suggested by nus:
/function (.{1,})\(/.exec(fun.toString())[1];

Remember that certain JavaScript minifiers may eliminate function names for better compression. Adjust the minifier's settings to prevent this if necessary.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3