Get name as String from a Javascript function reference?

前端 未结 8 2041
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: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"
    

提交回复
热议问题