How to get currently running function name using JavaScript ?
Given a function and the task is to get the name of function that is currently running using JavaScript.
- Approach 1: Using arguments.callee method: It refers to the currently executing function inside the function body of that function. In this method, we use arguments.callee to refer to the name of the function. So we define a new variable as arguments.callee.toString(). Then we use (variable_name).substr to get the function and then we display it as an alert.
Syntax:
arguments.callee.toString()
You may have to parse the name though, as it will probably include some extra junk.
Example 1: This example display currently running function using arguments.callee method.
<!DOCTYPE HTML>
<html>
<head>
<title>
How to get currently running
function
name using JavaScript ?
</title>
</head>
<body style =
"text-align:center;"
>
<h1 style =
"color:green;"
>
GeeksForGeeks
</h1>
<script>
function
GFGs() {
var
me = arguments.callee.toString();
me = me.substr(
'function '
.length);
me = me.substr(0, me.indexOf(
'('
));
alert(me);
}
GFGs();
</script>
</body>
</html>
Output:
- Approach 2: With the help of console.log method, we define a new function which returns the name of the function and call it the present function.
Syntax:
function getFuncName() { return getFuncName.caller.name } function teddy() { console.log(getFuncName()) } teddy()
Example 2: This example display currently running function using console.log method.
<!DOCTYPE html>
<html>
<head>
<title>
How to get currently running
function
name using JavaScript ?
</title>
</head>
<body style =
"text-align:center;"
>
<h1 style =
"color:green;"
>
GeeksForGeeks
</h1>
<script>
function
getFuncName() {
return
getFuncName.caller.name
}
function
teddy() {
console.log(getFuncName())
}
teddy()
</script>
</body>
</html>
Output:
Please Login to comment...