Get name as String from a Javascript function reference?

var x = function fooBar(){};
console.log(x.name);
// "fooBar"

function bar(callback){
    var name=callback.toString();
    var reg=/function ([^\(]*)/;
    return reg.exec(name)[1];
}

>>> function foo() { };
>>> bar(foo);
"foo"
>>> bar(function(){});
""

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];
    }
  });
}

var name = callback.name;

MDN:

The name property returns the name of a function, or an empty string for anonymous functions:

Live DEMO

Tags:

Javascript