locked
How to get the name of the function caller RRS feed

  • Question

  • Hi guys,

    I'm wondering if there's a fast way to get the name of  the caller of a function.

    I know that, when not called from the global scope,  inside a function  we've the caller property but it's a reference to the object function that represents the caller. So, in a string context, I've the source code of the complete function (name, arg. list and body code) not just the function name.

    Of course I can extract the name from this string but I would like to know if there's a simpler (and faster) way to perform this task (I need this info just for some logging..)

    THX a lot


    Thursday, March 13, 2008 1:59 PM

All replies

  •  

    None that I know of.  Whilst a function can have a name its optional. In JScript a function is built and optionally associated with an identifier hence the function itself doesn't have a name.

     

    Take a look at this:-

     

    Code Snippet

    function fnA()
    {
     trace()
     var a = 1
    }

    var fnB = function()
    {
     trace()
     var b = 2
    }

    fnA()
    fnB()


    function trace()
    {
     WScript.echo(getFunctionName(trace.caller))
    }

    function getFunctionName(fn)
    {
     var rgx = /^function\s+([^\(\s]+)/
     var matches = rgx.exec(fn.toString());
     return matches ? matches[1] : "(anonymous)"
    }

     

     

     

     

    In this code fnA is an identifier that is created when the function is built and is assigned the function as its value, this happens before code in this execution context is executed.  However fnB is merely a variable.  The function that is eventually assigned to it is anonymous and is not associated with an identifier.  fnB only receives the function as a value when that assignment is executed.  Hence if you moved the calls to fnA and fnB to the beginning of the script fnA would succeed by fnB doesn't have a value.

     

    The getFunctionName function is one example of retrieving the function name but as you're probably aware it ain't going to be quick.

     

     

    Thursday, March 13, 2008 3:44 PM