Last active
August 29, 2015 13:59
-
-
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
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 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