Get name as String from a Javascript function reference?

前端 未结 8 1965
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];
        }
      });
    }
    

提交回复
热议问题