+ 5
The purpose of JavaScript's arguments.callee()
I've read in Mozilla documentation that arguments.callee is the currently executing function. My question is what is its purpose, can you bring any real-life example of callee() usage?
5 Respuestas
+ 4
You're welcome.
Basically, an anonymous function is executed and doesn't have a name for itself to reference the function's execution (this is when callee becomes important because it CAN reference that function which doesn't have a name). As such, that makes it a pain to use a recursive function since you can't reference it, so you use callee as its reference to make the recursive function work.
Here is an example per Mozilla:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee
function create() {
return function(n) {
if (n <= 1)
return 1;
return n * arguments.callee(n - 1);
};
}
var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)
+ 4
Thanks Jakob for fast reply, can you please share some code example?
+ 4
Amazing explanation, thank you very much!
+ 3
It's no problem at all; you're welcome.
Take note that once upon a time this method was necessary when dealing with Javascript because it didn't have the appropriate feature to make up for it. However, that is no longer true today, and you would be better off simply naming your functions and referencing them in a normal manner. It's much more readable and easier on others who have to edit/use your code.
Best of luck to you in your learning!
+ 2
When you don't have named function expressions, you can use it to create an anonymous recursive function.