Thursday, June 21, 2012

[JScript] The name of the caller


A few postings back I demonstrated how to pull the name of the current function out of arguments.callee. Now to finding out the name of the caller:

function foo() {
 try {
  var myCaller = foo.caller.toString().split(/ /)[1].split(/\(/)[0];
 } catch( e ) {
  myCaller = e.message;
 }
 WScript.Echo(myCaller );

}

function bar() {
 foo();
}

bar();
foo();
The output from all that is
bar
'foo.caller' is null or not an object
So if foo is called from bar then myCaller contains "bar" otherwise an error is raised as the global context doesn't qualify as a "caller". Notice, too, that unlike getting the callee, the caller requires the name of the current function, not arguments.© Copyright Bruce M. Axtens, 2012

No comments: