Skip to content

Instantly share code, notes, and snippets.

@amoilanen
Last active August 29, 2015 13:59
Show Gist options
  • Save amoilanen/10601760 to your computer and use it in GitHub Desktop.
Save amoilanen/10601760 to your computer and use it in GitHub Desktop.
Simple function to determine the name of a JavaScript function in case https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name is not defined
function functionName(func) {
var match = func.toString().match(/function\s+([^(?:\()\s]*)/);
return match ? match[1] : "";
}
/*
* Tests
*/
var func1 = function(x, y) {
return x + y;
}
function func2(x, y) {
return x + y;
}
function func3 (x, y) {
return x + y;
}
[func1, func2, func3].forEach(function(func) {
console.log("function name = '" + functionName(func) + "'");
console.log("native function name = '" + func.name + "'");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment