skip to Main Content

I saw someone post this code:

function getFuncName() {
   return getFuncName.caller.name
}

Can someone plase explain what it means to use getFuncName inside the getFuncName function? Is there a reference for this in MDN web docs?

3

Answers


  1. I hope this will answer your question-

    So basically your code returns the caller function name –

    function callerFunction(){ 
    
       console.log(getFuncName())
    
    }
    

    The output of the above code is "callerFunction".

    Login or Signup to reply.
  2. Using the caller property is not recommended. The same goes for the callee property.

    function whoCalledMe() {
      return whoCalledMe.caller.name;
    }
    
    function iCalledYou() {
      console.log(whoCalledMe());
    }
    
    iCalledYou();

    If you enable strictness, the code will actually error:

    'use strict';
    
    function whoCalledMe() {
      return whoCalledMe.caller.name;
    }
    
    function iCalledYou() {
      console.log(whoCalledMe());
    }
    
    iCalledYou(); 

    If you really wanted to do this safely, you should just create your own call stack… But why would you need to do this?

    const callStack = [];
    
    function whoCalledMe() {
      return callStack.at(-1);
    }
    
    function iCalledYou() {
      callStack.push('iCalledYou'); // Push onto stack
      console.log(whoCalledMe());
      callStack.pop(); // Pop off stack
    }
    
    iCalledYou();
    Login or Signup to reply.
  3. Here the getFuncName() function returns the name of the function that called it.

    When you return getFuncName.caller.name you faced some issues
    If you are looking to get the name of the function that called another function, you might need another Method.

    get the name of the function that is called getFuncName, you can pass the function itself as an argument

    function getCallerName(func) {     
             return func.name; 
    }  
    function myFunction() {     
       console.log(getCallerName(myFunction)); 
    }  
     myFunction(); // Output: "myFunction"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search