Properties and arguments.callee arguments.callee.caller
calleeis a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.
Note: You should avoid using arguments.callee() and just give every function (expression) a name.
arguments.callee is an interesting property of arguments which references the function which is being run.
JavaScript implementations can optimize the code much better if they know that keepingarguments.callee is not required.
It will trigger error in “strict mode”, which you need to enable. Normally, it works.
For example, setTimeout(func, ms) is a built-in function which calls func after ms microseconds.
setTimeout(
function() { alert(1) }, // alerts 1 after 1000 ms (=1 second)
1000)
The function has no name. To call it recursively 3 times, let’s use arguments.callee:
var i = 1
setTimeout( function() {
alert(i)
if (i++<3) setTimeout(arguments.callee, 1000) }
1000)
Another example is factorial:
// factorial(n) = n*factorial(n-1)
var func = function(n) {
return n==1 ? 1 : n*arguments.callee(n-1)
}
The factorial function given above works even if func is reassigned to something else. That’s because it uses arguments.callee to reference itself.
arguments.callee.caller
The property arguments.callee.caller keeps the reference to a calling function.
There is a property arguments.caller with same meaning, but less supported. Don’t use it, stick to arguments.callee.caller, all browsers have it.
In the example below, arguments.callee.caller references the calling function of g, that is f.
f()
function f() { alert(arguments.callee.caller) // undefined g()}
function g() { alert(arguments.callee.caller) // f}
Static properties and methods
Static variables
There are languages which allow to put a static keyword before a variable, and then such variable is not cleared in next calls.
Example of a static variable in JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
function f() {
f.count = ++f.count || 1 // f.count is undefined at first
alert("Call No " + f.count)
}
f(); // Call No 1
f(); // Call No 2
Of course, a global variable can keep the counter, but static variables lead to a better architecture.
We could make the code more universal by replacing f with arguments.callee.