简体   繁体   中英

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?

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

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

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

You can extract the object and function name with:

function getFunctionName()
{
    return (new Error()).stack.split('\n')[2].split(' ')[5];
}

For example:

function MyObject()
{
}

MyObject.prototype.hi = function hi()
{
    console.log(getFunctionName());
};

var myObject = new MyObject();
myObject.hi(); // outputs "MyObject.hi"
var x = function fooBar(){};
console.log(x.name);
// "fooBar"

尝试访问.name属性:

callback.name 

If you were looking for the function on an specific object event, this may help:

var a = document.form1
a.onsubmit.name

for me, with just a little modification (adding \\ before parent), this work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM