Return to Snippet

Revision: 67300
at September 5, 2014 19:20 by zandor


Updated Code
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
Function.prototype.myname = function() { return this.toString().substr( 0, this.toString().indexOf( "(" ) ).replace( "function ", "" ) ; }
Function.prototype.callername = function( _level )
{
     // level 0 is this functon
     _level = parseInt( _level, 10 );      if ( isNaN( _level ) || _level < 0 ) _level = 0 ;
     var _eval_str = "arguments.callee" ;
     for( var _l = 0 ; _l <= _level ; _l++ ) _eval_str += ".caller" ;
     
     _eval_str += ".myname();" ;
     return eval( _eval_str ) ;
}

function _child_caller()
{
    document.write( "This function is " + arguments.callee.callername(0) ) ;
    document.write( "<br>" );
    document.write( "Parent function is " + arguments.callee.callername(1) ) ;
    document.write( "<br>" );
    document.write( "Grand Parent function is " + arguments.callee.callername(2) ) ;
}

function _parent_caller()
{
    _child_caller() ;
}

function _grand_parent_caller()
{
    _parent_caller() ;
}

_grand_parent_caller();
</SCRIPT>

Revision: 67299
at September 5, 2014 19:18 by zandor


Initial Code
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
Function.prototype.myname = function() { return this.toString().substr( 0, this.toString().indexOf( "(" ) ).replace( "function ", "" ) ; }
Function.prototype.callername = function( _level )
{
     // level 0 is this functon
     _level = parseInt( _level, 10 );      if ( isNaN( _level ) || _level < 0 ) _level = 0 ;
     var _eval_str = "arguments.callee" ;
     for( var _l = 0 ; _l <= _level ; _l++ ) _eval_str += ".caller" ;
     
     _eval_str += ".myname();" ;
     console.log( _eval_str );
     return eval( _eval_str ) ;
}

function _child_caller()
{
    document.write( "This function is " + arguments.callee.callername(0) ) ;
    document.write( "<br>" );
    document.write( "Parent function is " + arguments.callee.callername(1) ) ;
    document.write( "<br>" );
    document.write( "Grand Parent function is " + arguments.callee.callername(2) ) ;
}

function _parent_caller()
{
    _child_caller() ;
}

function _grand_parent_caller()
{
    _parent_caller() ;
}

_grand_parent_caller();
</SCRIPT>

Initial URL

                                

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

Initial Title
Recursive parental function callers

Initial Tags
javascript, function

Initial Language
JavaScript