bloqhead
8/29/2013 - 10:58 PM

get a javascript function name

get a javascript function name

function getFnName(fn) {
  var f = typeof fn == 'function';
  var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
  return (!f && 'not a function') || (s && s[1] || 'anonymous');
}

console.log(getFnName(String)); // 'String'
console.log(getFnName(function test(){})); // 'test'

console.log(getFnName(function (){})); // 'anonymous'
console.log(getFnName(function(){})); // 'anonymous'
console.log(getFnName(Function())); // 'anonymous'

console.log(getFnName({name: 'test'})); // 'not a function'
console.log(getFnName('test')); // 'not a function'