Obtaining the Name of the Current Function in JavaScript
Can you dynamically access the name of the currently executing function in JavaScript?
Problem Description
Consider the following example:
<code class="javascript">myfile.js: function foo() { alert(<my-function-name>); // pops-up "foo" // or even better: "myfile.js : foo" }</code>
The goal is to retrieve the function's name and possibly its full location (filename:function-name). Is this achievable?
Solution
In ES5 and Later: Unfortunately, there is no built-in mechanism to obtain the function's name in ES5 and subsequent versions.
In Older JavaScript Versions: In earlier versions of JavaScript, it was possible to access the function name using arguments.callee. However, this approach might require some parsing as the returned value may include extraneous information.
Parsing Approach:
<code class="javascript">function DisplayMyName() { var myName = arguments.callee.toString(); myName = myName.substr('function '.length); myName = myName.substr(0, myName.indexOf('(')); alert(myName); }</code>
Source: [Javascript - get current function name](https://stackoverflow.com/questions/4267180/javascript-get-current-function-name)
The above is the detailed content of How to Dynamically Get the Name of the Current Function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!