Home  >  Article  >  Web Front-end  >  How to Dynamically Get the Name of the Current Function in JavaScript?

How to Dynamically Get the Name of the Current Function in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 15:27:30557browse

How to Dynamically Get the Name of the Current Function in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn