How to get the function name from within that function?

前端 未结 20 1140
抹茶落季
抹茶落季 2020-11-22 16:06

How can I access a function name from inside that function?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  p         


        
20条回答
  •  执笔经年
    2020-11-22 16:32

    It looks like the most stupid thing, that I wrote in my life, but it's funny :D

    function getName(d){
      const error = new Error();
      const firefoxMatch = (error.stack.split('\n')[0 + d].match(/^.*(?=@)/) || [])[0];
      const chromeMatch = ((((error.stack.split('at ') || [])[1 + d] || '').match(/(^|\.| <| )(.*[^(<])( \()/) || [])[2] || '').split('.').pop();
      const safariMatch = error.stack.split('\n')[0 + d];
    
      // firefoxMatch ? console.log('firefoxMatch', firefoxMatch) : void 0;
      // chromeMatch ? console.log('chromeMatch', chromeMatch) : void 0;
      // safariMatch ? console.log('safariMatch', safariMatch) : void 0;
      
      return firefoxMatch || chromeMatch || safariMatch;
    }
    

    d - depth of stack. 0 - return this function name, 1 - parent, etc.;
    [0 + d] - just for understanding - what happens;
    firefoxMatch - works for safari, but I had really a little time for testing, because mac's owner had returned after smoking, and drove me away :'(

    Testing:

    function limbo(){
      for(let i = 0; i < 4; i++){
        console.log(getName(i));
      }
    }
    function lust(){
      limbo();
    }
    function gluttony(){
      lust();
    }
    
    gluttony();
    

    Result:
    Chrome:

    Fitefox:

    This solution was creating only just for fun! Don't use it for real projects. It does not depend on ES specification, it depends only on browser realization. After the next chrome/firefox/safari update it may be broken.
    More than that there is no error (ha) processing - if d will be more than stack length - you will get an error;
    For other browsers error's message pattern - you will get an error;
    It must work for ES6 classes (.split('.').pop()), but you sill can get an error;

提交回复
热议问题