JavaScript: getting function name

JavaScript doesn't provide a native method to get the name of a function. Some browsers have implemented a name property attached to the Function object, but this doesn't work in a cross-browser fashion. So far, we've forced to augment the basic Function object to get the desired result. The code is as follows:

if(Function.prototype.getFuncName !== 'function') {


  Function.prototype.getFuncName = function() {
  
  
    var name = '';
    var self = this;
    var string = self.toString();
    
    var sanitized = string.replace(/\s+/g, '').
                    replace('function', '').
                    replace('(', '').
                    replace(')', '');
    
    var re = /.+\{/;
    
    var matches = sanitized.match(re);
    
               
    name = matches[0].replace('{', '');
    
    return name;
  
  
  };


}

We use the string representation of a function and a couple of regular expressions to extract the function name. A simple test:

window.onload = function() {

function func() {
 alert('OK');
}

function methodForTest () {

  return;

}

alert(func.getFuncName()); // func
alert(methodForTest.getFuncName()); //methodForTest

};

You can see the demo below.

Demo

Live demo

One thought on “JavaScript: getting function name”

Leave a Reply

Note: Only a member of this blog may post a comment.