| Web Developer Resources | |
Learning JavaScript: How to find function name from inside of itself
It's rare, but occasionally it's helpful to discover a JavaScript function's name from inside of itself.
Even with years of JavaScript experience, I find myself having to hunt this technique down, and then the examples are
never precisely what I'm after, so they need to be tweaked...it's all a big time suck. So, hopefully this will make it
easier to find this in the future, and if it helps you that's even better.
If you have suggestions, please let me know, feedback is appreciated. Enjoy.
The trick I've found helpful is to regex match the stringified output of the arguments object's callee property...long breath.
Whose obscure nightmare the object naming came out of I have no idea, but there it is. The usefulness of this technique is that it can be
used to construct agnostic recursive function calls, or delayed calls to return to a function after some period of time.
arguments.callee.toString().match(/function ([^\(]+)/)[1]
<script type="text/javascript"> /* create functions that can report their own names, by looking into the arguments used to invoke them */
function FunctionA(){ var fName = arguments.callee.toString().match(/function ([^\(]+)/)[1] alert('Hi, I\'m in a function named '+fName) }
function FunctionB(){ alert(arguments.callee.toString().match(/function ([^\(]+)/)[1]); }
function FunctionC(){ FunctionA(); FunctionB(); } </script>
Try it out here. Each of these links calls a function which then displays a parsed version of the callee property of the arguments object.
The test will allow you to sanity check whether the technique works in your browser's JavaScript engine.
Functions:
Call FunctionA,
Call FunctionB,
Call FunctionC
Additional Keywords:
learning, javascript,
current function name,
create recursive call to this method,
how to make a delayed function call to self
|