Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-21 15:27:30
Original
676 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template