-
-
Save morgant/054cb3f38c3075479ff6349c5fa50560 to your computer and use it in GitHub Desktop.
get a javascript function name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
function currentFnName() { | |
try { | |
return getFnName(arguments.caller); | |
} catch(e) { | |
var s = new Error().stack.split('\n'); | |
var m = /(^[^@]+)@/.exec(s[1]); | |
return ((s.length > 1) && m && (m.length > 1)) ? m[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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment