Last active
October 31, 2022 11:44
-
-
Save dfkaye/6384439 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) { | |
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