Get name as String from a Javascript function reference?

前端 未结 8 2006
Happy的楠姐
Happy的楠姐 2020-12-25 11:27

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)
{
           


        
相关标签:
8条回答
  • 2020-12-25 12:08

    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];
        }
      });
    }
    
    0 讨论(0)
  • 2020-12-25 12:10
    var name = callback.name;
    

    MDN:

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

    Live DEMO

    0 讨论(0)
  • 2020-12-25 12:11

    try to access the .name property:

    callback.name 
    
    0 讨论(0)
  • 2020-12-25 12:13

    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];
        }
      });
    }
    
    0 讨论(0)
  • 2020-12-25 12:17
    var x = function fooBar(){};
    console.log(x.name);
    // "fooBar"
    
    0 讨论(0)
  • 2020-12-25 12:19

    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"
    
    0 讨论(0)
提交回复
热议问题