Recursive parental function callers


/ Published in: JavaScript
Save to your folder(s)

This snippet allows to know the parent function caller name of any level from the calling function.


Copy this code and paste it in your HTML
  1. <SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
  2. Function.prototype.myname = function() { return this.toString().substr( 0, this.toString().indexOf( "(" ) ).replace( "function ", "" ) ; }
  3. Function.prototype.callername = function( _level )
  4. {
  5. // level 0 is this functon
  6. _level = parseInt( _level, 10 ); if ( isNaN( _level ) || _level < 0 ) _level = 0 ;
  7. var _eval_str = "arguments.callee" ;
  8. for( var _l = 0 ; _l <= _level ; _l++ ) _eval_str += ".caller" ;
  9.  
  10. _eval_str += ".myname();" ;
  11. return eval( _eval_str ) ;
  12. }
  13.  
  14. function _child_caller()
  15. {
  16. document.write( "This function is " + arguments.callee.callername(0) ) ;
  17. document.write( "<br>" );
  18. document.write( "Parent function is " + arguments.callee.callername(1) ) ;
  19. document.write( "<br>" );
  20. document.write( "Grand Parent function is " + arguments.callee.callername(2) ) ;
  21. }
  22.  
  23. function _parent_caller()
  24. {
  25. _child_caller() ;
  26. }
  27.  
  28. function _grand_parent_caller()
  29. {
  30. _parent_caller() ;
  31. }
  32.  
  33. _grand_parent_caller();
  34. </SCRIPT>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.