I am getting the caller function's information through
arguments.callee.caller
But if I want to call the caller function again, what I have to do?
I am getting the caller function's information through
arguments.callee.caller
But if I want to call the caller function again, what I have to do?
Simply call that function again.
arguments.callee.caller()
example:
function A(){
B();
}
function B(){
arguments.callee.caller(); // It will call the A again.
}
Inside the function arguments.callee.caller
is a reference to the caller function, in fact typeof arguments.callee.caller === 'function'
so you can call it directy:
arguments.callee.caller(arg1, arg2, arg3, [...]);
Or you could do this:
arguments.callee.caller.call(context, arg1, arg2, arg3, [...]);
Or this:
arguments.callee.caller.apply(context, [arg1, arg2, arg3, [...]]);
As other said, beware of performance hits though!
My first hint is this:
var nm = arguments.callee.caller.name
And then call "nm". Using eval or with some switch-cases.
Watch out for infinite loops:
// The 'callee'
function f(arg) {
var cf = arguments.callee.caller;
cf.call(42);
}
// .. and the caller
function g(arg) {
if (arg === 42) {
alert("The Answer to..");
} else {
f(1); // or whatever
}
}
// call the caller
g(21)
You should favour Function.caller over arguments.callee.caller (not least because people can't make their minds up about whether or not this is deprecated)
Why was the arguments.callee.caller property deprecated in JavaScript?
To exemplify the usage:
var i = 0;
function foo () {
bar();
}
function bar() {
if ( i < 10 ) {
i += 1;
bar.caller();
}
}
foo();
// Logs 10
console.log(i);
Though in the real world you might want to check that caller is a function before calling it.