JavaScript By Example

106 43
An argument list not only has the numbered elements corresponding to the passed parameters and the length that tells you how many there are, it also contains one more property which provides a way to reference the function itself - callee.

It is recommended that the use of this particular property be avoided as much as possible since there are in almost all instances better ways of referencing the function (such as referencing it by its name).

The only situation where you can't reference a function by its name is where you have an anonymous function and so the only situations where you could ever possibly need to use callee is where you have an anonymous function.

Even with anonymous functions using callee is seldom required since an anonymous function can normally only be run once as a self executing function (as otherwise you'd give it a name so as to make it easier to call it on subsequent occasions). Where an anonymous function is only run the once then the variables etc. associated with the function can be easily referenced by their names. It is only where you are going to run an anonymous function more than once and need for values to be retained between the calls that you'd need to use callee in order to reference them.

In this example we have the bare minimum of code necessary to demonstrate the extremely rare situation where using callee would be necessary. We have a self executing anonymous function which is displaying an alert just so that we can see that it is being called (you'd replace the alert with whatever the function is supposed to be doing.

The function has one property "done" which is retained between executions of the functions that the value set during one execution of the function can be tested on subsequent calls. we have a test in the function for if this property is set to true to determine when to exit from the function. Finally the function recursively calls itself when it finishes running. The end result of this convoluted code that demonstrates where callee would actually be required is that the alert runs twice.

(function() {
  alert('called');
  if (arguments.callee.done) return;
  arguments.callee.done = true;
  arguments.callee();
})();


Note that alert is used here for the purpose of simplifying the example. You should never use alert() in your own code for anything other than displaying results during testing.
Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.