Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active October 31, 2022 11:44
Show Gist options
  • Save dfkaye/6384439 to your computer and use it in GitHub Desktop.
Save dfkaye/6384439 to your computer and use it in GitHub Desktop.
get a javascript function name
function getFnName(fn) {
fn = Object(fn)
var F = typeof fn == 'function'
var N = fn.name
var S = F && ((N && ['', N]) || 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(() => {})); // 'anonymous'
console.log(getFnName({ name: 'test' })); // 'not a function'
console.log(getFnName('test')); // 'not a function'
console.log(getFnName()) // 'not a function'
console.log(getFnName(null)) // 'not a function'
try {
console.log(getFnName(Function())); // 'anonymous'
} catch(e) {
console.error("eval() not supported")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment