Search code examples
javascript

Get name as String from a Javascript function reference?


I want to do the opposite of Get JavaScript function-object from its name as a string?

That is, given:

function foo()
{}

function bar(callback)
{
  var name = ???; // how to get "foo" from callback?
}

bar(foo);

How do I get the name of the function behind a reference?


Solution

  • If you can't use myFunction.name then you can:

    // Add a new method available on all function values
    Function.prototype.getName = function(){
      // Find zero or more non-paren chars after the function start
      return /function ([^(]*)/.exec( this+"" )[1];
    };
    

    Or for modern browsers that don't support the name property (do they exist?) add it directly:

    if (Function.prototype.name === undefined){
      // Add a custom property to all function values
      // that actually invokes a method to get the value
      Object.defineProperty(Function.prototype,'name',{
        get:function(){
          return /function ([^(]*)/.exec( this+"" )[1];
        }
      });
    }